C #: AsyncCallback not being called on Socket.BeginReceive

I have a serious problem with the asynchronous method of getting System.Net.Sockets.Socket.

Here is the code I use to open the connection:

_socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_socket.Connect(endpoint);

byte[] buffer = new byte[1024];
_socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, buffer);

and here is the callback method:

private void ReceiveCallback(IAsyncResult result)
{
     byte[] buffer = (byte[])result.AsyncState;
     int count = _socket.EndReceive(result);

     if (count > 0)
     {
          // Do something
     }

     buffer = new byte[1024];
     _socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, buffer);
}

The problem is that ReceiveCallback is never called despite a socket connection.

Can anyone help me on this?

+3
source share
1 answer

First of all, do not ignore if it EndRecievereturns 0 bytes. This means that the connection was closed by the remote endpoint.

Are you sure the remote endpoint sent you something? My bet is that it is not.

, , .

, . .

+3

Source: https://habr.com/ru/post/1754571/


All Articles