Sandeep Pathak
Sandeep Pathak

Reputation: 10747

Problem sending multiple strings one by one using sockets

I am new to socket programming. Need to send multiple strings one-by-one to server and collect the resulting string.

Now the problem is that using send/write function in client, all the strings are read in one go from server.

//client.c
sendString(serversocket,"str1"); 

sendString(serversocket,"str2"); 

sendString(serversocket,"str3"); 

//server.c

char *buff=readstring(clientsocket);

printf("%s",buff) ;//output : str1str2str2

Need to get str1, str2 and str3...

I need to make it as receive one after another. How can I do this? Any help would be appreciated.

Upvotes: 1

Views: 3541

Answers (3)

Robert S. Barnes
Robert S. Barnes

Reputation: 40558

Since TCP is a byte stream you need to delimit your pieces of data, i.e. your logical packets. In this case a newline character '\n' may be the most obvious choice, or you could use the null charater, '\0'.

//client.c
sendString(serversocket,"str1\n"); 

sendString(serversocket,"str2\n"); 

sendString(serversocket,"str3\n"); 

You could then use something like strtok to chop up the input data into it's component logical packets.

Upvotes: 0

Nick
Nick

Reputation: 25799

I assume you're using TCP here. In which case anything sent to the socket is treated as a stream. So you'll have to add separators into the stream in order to split the strings. You could send a newline after each string and then parse the input to split the lines again.

Upvotes: 0

Erik
Erik

Reputation: 91270

A TCP socket is a byte stream - You will have to split up the data on the receiving end.

For strings, you can do this in e.g. one of these two ways:

Client:

  • send an integer length
  • send the string data

Server:

  • read an integer length
  • read this amount of bytes into a string

Or, you can use 0-termination:

Client:

  • send a string followed by a 0 byte

Server:

  • Read as much as possible, scan for 0 byte, extract string

You will have to handle both of these two cases on the server end:

  • Server receives 1 byte for each call to recv()
  • Server receives all data in a single call to recv()

Upvotes: 3

Related Questions