开发者

C#: AsyncCallback not being called on Socket.BeginReceive

I have a serious problem with the asynchronous Receive method of System.Net.Sock开发者_开发百科ets.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 the ReceiveCallback is never being called, despite the socket being connected.

Can anyone help me out on this one?


First of all, do not ignore if EndRecieve returns 0 bytes. It means that the connection have been closed by the remote end point.

Are you sure that the remote endpoint have sent something to you? My bet is that that is not the case.

I've done quite a few socket applications and I have never had any problems with the callback not being called.

It's also very important that you handle exceptions in callback methods. Not doing so will make your application crash when an exception is being thrown.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜