从异步套接字接收完整数据

时间:2017-05-30 14:47:02

标签: c# sockets asynchronous networking

我有这个代码(见下文),受到https://msdn.microsoft.com/en-us/library/bbx2eya8.aspx的广泛启发 代码应该从存储在缓冲区中的客户端获取完整请求,所有这些都是在异步上下文中完成的。 请注意,以下代码首次使用时调用:
state.SourceSocket.BeginReceive(new AsyncCallback(ReceiveFromClient), state);

    private static void ReceiveFromClient(IAsyncResult result)
    {
        var state = result.AsyncState as State;
        try
        {
            var bytesRead = state.SourceSocket.EndReceive(result);
            if (bytesRead > 0)
            {
                state.sb.Append(Encoding.ASCII.GetString(state.Buffer, 0, bytesRead));
                // here I try to get some more data if needed
                state.SourceSocket.BeginReceive(new AsyncCallback(ReceiveFromClient), state);
                // this stands for _socket.BeginReceive(state.Buffer, 0, state.BufferSize, 0, callback, state);

            }
            else if (state.sb.Length > 1)
            {
                Console.WriteLine("Now sending the received message");
                state.bufferString = state.sb.ToString();
                state.DestinationSocket.BeginSend(new AsyncCallback(SendToRemote), state);
            }
        }
        // uninteresting catch block
    }

为了清楚起见,这是State课程

public class State
{
    public Socket SourceSocket { get; private set; }
    public Socket DestinationSocket { get; private set; }

    public int BufferSize;
    public byte[] Buffer { get; private set; }
    public string bufferString;
    public StringBuilder sb = new StringBuilder();

    public State(Socket source, Socket destination, int bufferSize)
    {
        SourceSocket = source;
        DestinationSocket = destination;
        Buffer = new byte[bufferSize];
        BufferSize = bufferSize;
    }
}

问题如下:
第一次调用ReceiveFromClient似乎工作正常,我得到了一些数据,但是当我第二次调用BeginReceive时根本没有发生任何事情,我甚至没有再次进入回调。
请注意,这可能是一个初学者错误,因为这是我第一次处理c#应用程序。

0 个答案:

没有答案