Hi!
At the moment I am coding a little server-tool in C# using the .NET Framework 2.0. Everything works fine, but I encounter a very strange problem when packets for one connection are received nearly at the same time. When you look at the Connection-class you will see that I count the packets I received. When two packets are received nearly at the same time one of those packets gets ignored! It looks like it is never ever received by my server.
Okay. I found the solution myself. I was too stupid to think of TCP being a stream-oriented protocol. I always read the first packet in the buffer and didn't care of other packets that could have been in the buffer, too. Well... now it works ;)
This is the code where I start listening for incoming connections:
And here are my callbacks:Code:listener.Bind(localEndPoint); // listener is my listen-socket listener.Listen(5); while (true) { allDone.Reset(); Console.WriteLine("Waiting for connection..."); listener.BeginAccept(new AsyncCallback(AcceptCallback), listener); allDone.WaitOne(); }
The class Connection is the class that encapsulates the details for every connection. It looks like this (this is a shortened version):Code:AcceptCallback(IAsyncResult ar) { allDone.Set(); Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); Connection state = new Connection(); state.ClientSocket = handler; state.Buffer = new byte[Connection.Buffersize]; handler.BeginReceive(state.Buffer, 0, Connection.Buffersize, 0, new AsyncCallback(ReadCallBack), state); } ReadCallback(IAsyncResult ar) { Connection state = (Connection)ar.AsyncState; Socket handler = state.ClientSocket; int byteRead = handler.EndReceive(ar); if (byteRead > 0) { state.Process(state.Buffer); // This call could take some time } handler.BeginReceive(state.Buffer, 0, Connection.Buffersize, 0, new AsyncCallback(ReadCallBack), state); }
I hope you can help me. This is really annoying and it starts to piss me off :bad:Code:class Connection { public const int Buffersize = 1024; public int packetsreceived = 0; public Socket ClientSocket; public byte[] Buffer; public void Process(byte[] packetdata) { // Process the packet. Can take some time } }
Thanks for you help.Cheers!:smilie_xp


Reply With Quote![[SOLVED | C# | .NET 2.0] Issue with asynchronous socket I/O](http://ragezone.com/hyper728.png)

