views:

213

answers:

2

i would like some help with the following. this is to do with Asynchronous sockets.

from the sender:

string stringData = "Welcome to my server server server";
byte[] message1 = Encoding.ASCII.GetBytes(stringData);

//MessageBox.Show(message1.Length.ToString());

client.BeginSend(message1, 0, message1.Length, SocketFlags.None, new AsyncCallback(SendData), client);

here as can be seen, the message.length can be found.

--

on the client:

  Socket remote = (Socket)iar.AsyncState;
  int recv = remote.EndReceive(iar);
  string stringData = Encoding.ASCII.GetString(data, 0, recv);

my question is is there a way to access the actual length of the sent data and based on that call recieve data until the complete message is recieved?

A: 

Only if something is transmitted to communicate the length - either pre-pend the length to the message, or send a terminator character of some kind.

David M
+7  A: 

No - TCP/IP is a stream protocol. Just because you've sent the data with one call doesn't mean it will be sent as one packet, or that it won't be merged with other packets. In other words, sending "X" then "Y" is equivalent to sending "XY" - they may well be transmitted with the exact same packets, indistinguishable to the other end.

If you want the idea of an individual "message" in a stream, you should prefix the data with a few bytes explicitly stating its length. (An alternative is to use a delimiter, but I far prefer using a length prefix - it makes it easier to know how much data you've still got to receive, you don't need to worry about starting to consume the next message, and you don't have to worry about escaping the delimiter in some form.)

Jon Skeet
instead of prefixing i just implemented a loop as stated here http://stackoverflow.com/questions/582550/c-begin-endreceive-how-do-i-read-large-data. it seems to be working! :)
iEisenhower
You can only just keep looping if you want to receive all of the data until the socket is closed - otherwise you won't know when you've *actually* seen it all. That's fine if you're just doing a single request/response on the connection, but it doesn't work for a "conversation" type of protocol with multiple messages in each direction.
Jon Skeet