异步接收Socket数据

#region 异步接收Socket数据
/// <summary>
/// 异步接收Socket数据
/// </summary>
/// <param name="socket"></param>
/// <returns></returns>
public static byte[] ReceiveData(Socket socket)
{
    ReceiveObject state = new ReceiveObject() { Client = socket };
    socket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), state);
    state.ReceiveDone.WaitOne(1000 * 10); // 10秒超时
    byte[] result = state.Stream.ToArray();
    return result;
}

/// <summary>
/// 同步接收对象
/// </summary>
private class ReceiveObject
{
    public Socket Client;
    public byte[] Buffer = new byte[4096];
    public System.IO.MemoryStream Stream = new System.IO.MemoryStream();
    public System.Threading.ManualResetEvent ReceiveDone = new System.Threading.ManualResetEvent(false);
}

/// <summary>
/// read回调
/// </summary>
/// <param name="ar"></param>
private static void ReadCallback(IAsyncResult ar)
{
    ReceiveObject state = (ReceiveObject)ar.AsyncState;
    int bytesRead = state.Client.EndReceive(ar);
    if (bytesRead > 0)
    {
        try
        {
            state.Stream.Write(state.Buffer, 0, bytesRead);
            state.Client.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), state);
        }
        catch (Exception ex)
        {
            Log.Error(ex.Message);
            state.ReceiveDone.Set();
        }
    }
    else
    {
        state.ReceiveDone.Set();
    }
}
#endregion

posted @ 2011-07-04 16:31  ahui  阅读(5734)  评论(0编辑  收藏  举报