Search code examples
c#socketsdisconnect

Receive all data if connection is closed early


I have a client that connects to server, starts sending binary data and when it's done sending, it closes the connect. If connection is closed the server knows client is done sending the file.

I have a simple tcp class to handle the connection. Then I have another function that sends data to server:

  TcpC tcp = new TcpC();

  void send_data_to_server(){
        tcp.connect();

        while(read_data){
            tcp.sendData();
        }

        Thread.Sleep(500);
        tcp.disconnect();
  }

Server uses async sockets and has a function WaitForData() which gets exception when client disconnects. The problem is if I remove the Thread.Sleep() WaitForData still catches the exception, but onDataReceive still hasn't received all the data because I check the buffer size in exception and it's much smaller than if I use Sleep().

The server is going to have to handle many operations like this and I cannot afford to use Sleep() 'hack' for it to work. Sometimes it doesn't work anyway and I have to set sleep interval to couple of seconds to be sure. None of the other async functions on the server side trigger exception except WaitForData().

How can I close the connection immediately and still get all the data? I though tcp.disconnect is called after all the data is sent anyway so I'm not clear why am I having this issue. Thanks!


Solution

  • From the MSDN Docs:

    To ensure that all data is sent and received before the socket is closed, you should call Shutdown before calling the Disconnect method.

    It might be worth giving that a shot.

    Otherwise if your code snippet is any indication (based on your use of TcpC), you should probably be using TcpClient.Close which I believe will do this for you.