[SOLVED | C# | .NET 2.0] Issue with asynchronous socket I/O

Results 1 to 1 of 1
  1. #1
    Member ingam0r is offline
    MemberRank
    Sep 2006 Join Date
    93Posts

    Cool [SOLVED | C# | .NET 2.0] Issue with asynchronous socket I/O

    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:

    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();
    }
    And here are my callbacks:
    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);
    }
    The class Connection is the class that encapsulates the details for every connection. It looks like this (this is a shortened version):
    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
       }
    }
    I hope you can help me. This is really annoying and it starts to piss me off :bad:

    Thanks for you help.Cheers!:smilie_xp
    Last edited by ingam0r; 31-10-06 at 12:33 AM. Reason: Solved my problem




Advertisement