如何使用Socket.BeginReceive Overload 3?

时间:2014-06-30 21:10:02

标签: c# .net sockets asynchronous

您好我想将方法​​Socket.BeginReceive(Byte[], Int32, Int32, SocketFlags, AsyncCallback, Object)用于async服务器。我只是想知道如何为AsyncCallback设置我的方法来获取缓冲区。

我设置如下:

socket.BeginReceive(buffer, 0, size, SocketFlags.None, new AsyncCallback(receive), someObject);

public void receive(IAsyncResult ar) {
    // How to get buffer?
}

如果我在receive方法中添加一个参数,我会收到一个错误。那么我应该如何设置方法呢?在MSDN上没有任何方法可以做到这一点!

1 个答案:

答案 0 :(得分:0)

您可以使用state参数:

socket.BeginReceive(buffer, 0, size, SocketFlags.None, receive, buffer/*state*/);

public void receive(IAsyncResult ar) {
    // How to get buffer:
    var buffer = (byte[])ar.AsyncState;

    var bytesRead = socket.EndReceive(ar);

}