none
Socket Connection received data but the AsyncCallback keeps running RRS feed

  • Question

  • Hello

    I have a TCP client connection setup in my code. In my receiveCallback function, I print out the number of bytes received.

    The issue is, when I'm sent data, I receive all of it.  I'm able to see the count value increase up to the number of bytes sent, but then I keep seeing Count = xx repeatedly even thou no more data is being sent.

    Count 127528

    Connection from 192.168.111.113:3000

    Count 130688

    Connection from 192.168.111.113:3000

    Count 134112

    Connection from 192.168.111.113:3000

    Count 135168

    Connection from 192.168.111.113:3000

    Count 135168

    Connection from 192.168.111.113:3000

    Count 135168

    Connection from 192.168.111.113:3000

    Count 135168

    It never break out of this loop where the count is 135168.  Any ideas?

    tcpClient = new TcpClient("192.168.111.110", 1234);
                            state.workSocket = tcpClient.Client;
                            if (tcpClient.Connected)
                            {
                                LogIt.Output("Connected", true);
                                tcpClient.Client.BeginReceive(rcvBuffer, 0, StateObject.buffersize, 0, new AsyncCallback(receiveCallback), state);
                            }
     void receiveCallback(IAsyncResult ar)
            {
                int bytesRead = 0;
                state = (StateObject)ar.AsyncState;
                Socket handler = state.workSocket;
                if (handler.Connected)
                {
                    LogIt.Output("Connection from " + state.workSocket.RemoteEndPoint.ToString(),true);
                    bytesRead = handler.EndReceive(ar);
                    count += bytesRead;
                    LogIt.Output("Count " + count.ToString(),true);
                    Array.Copy(rcvBuffer, 0, dstBuffer, dstindex, bytesRead);
                    srcindex = bytesRead;
                    dstindex = count;
                    handler.BeginReceive(rcvBuffer, 0, StateObject.buffersize, 0, new AsyncCallback(receiveCallback), state);
                }
            } //end receiveCallback
     public class StateObject
        {
            public Socket workSocket = null;
            public const int buffersize = 174080;
            public byte[] buffer = new byte[buffersize];
            public StringBuilder sb = new StringBuilder();
        }

    Wednesday, February 20, 2013 4:04 PM

Answers

  • A connection will stay open forever even if no data is being transmitted unless the connection is closed in software.  If the keepalive setting is true (either on client of server) messages with no data will be sent.  Nomally in the CallBack you should check the byte count and ignore any messages with zero bytes.


    jdweng

    • Marked as answer by William256 Wednesday, February 20, 2013 5:56 PM
    Wednesday, February 20, 2013 4:41 PM