简体   繁体   中英

C# Sockets. Sending data through TCP/IP on slow connections

I have a TCP/IP connection between a server and a client. Once the connection is established, the server will start sending a lot of data to the client. The problem that I'm having is if the connection is slow, at some point the server will become unresponsive. I guess this is because it's buffering data waiting for the data that has already been sent to be acknowledged.

Is there are way before trying to send data to check the size of the current buffer, so I know I should wait before continuing sending data?

Thanks.

This is what I'm doing to send data:

System.Net.Sockets.Socket ClientSocket;
...  
public void Send(byte[] data, int size)
    {
        try
        {
            SocketAsyncEventArgs e = new SocketAsyncEventArgs();
            e.SetBuffer(data, 0, size);
            bool pending = ClientSocket.SendAsync(e);
        }
        catch (Exception ex)
        {

        }
    }

The documentation for SendAsync says that it will raise the SocketAsyncEventArgs.Completed event on the e parameter when the operation is complete. So if you write an event handler that responds to that event, you can always know how many operations you have outstanding.

There's a reasonably good example of using the event here: http://msdn.microsoft.com/en-us/library/system.net.sockets.socketasynceventargs.aspx

I found the solution. Basically I should only send data when

ClientSocket.Poll(0, SelectMode.SelectWrite) is true.

Easy and effective!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM