|
-
January 6th, 2007, 11:47 AM
#1
Asynchronous socket receive
Hi all!
I'm doing a server app in C# and have a little problem/question:
I call BeginReceive() method specifying the callback method. In the callback method, I call EndReceive() like this:
Code:
private void OnReceive(IAsyncResult ar)
{
User user = (User) ar.AsyncState;
int datalen = user.userSocket.EndReceive(ar);
Packet datapacket = new Packet();
datapacket.FromBytes(user.data);
HandlePacket(datapacket);
}
Now I read some articles and found out that data won't always arrive in packets, since TCP is a streaming protocol.
So my question is: what is the best way to ensure that I receive the full packet before trying to parse them?...
My data packets look like this: 2byte signature, 2bytes defining message type, 2 bytes representing a short value, which tells us how many more bytes the packet has.
So I can easily count the packet size: 6 + (the value that short holds) bytes.
Please tell me if you need some more info.
Thanks in advance!
Using .NET 2.0 
-
January 6th, 2007, 12:23 PM
#2
Re: Asynchronous socket receive
tcp uses packets. receive is unblocked when such a packet is received. tcp is a streamed protocol meaning that its a 1:1 2 way connection w/ another peer. data still has to be packaged up to be sent over the wire (and is how tcp is a transmission controlled protocol because it uses those layers of the packet to verify its payload).
tcp packets are not a fixed size and you're not guaranteed to have a complete anything. you'll need to buffer your data until you can verify that you've received everything (which is why tcp is not the final application layer... thats up to you).
-
January 6th, 2007, 02:09 PM
#3
Re: Asynchronous socket receive
Ok, I implemented data buffering, like You said, thanks for the tip. 
Now, what about BeginSend()? Does it require this special way of sending data (checking if all is sent), or does it call the callback method only when all the data is sent (1024 bytes are sent for example)?
Using .NET 2.0 
-
January 6th, 2007, 02:23 PM
#4
Re: Asynchronous socket receive
its called when all data has been sent.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|