Socket 데이터를 비동기적으로 수신

1645 단어 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

좋은 웹페이지 즐겨찾기