异步C#服务器从多个套接字连续读取数据

异步C#服务器从多个套接字连续读取数据,c#,sockets,networking,C#,Sockets,Networking,我使用的是在这里找到的MSDN服务器示例 我的问题是,这段代码只会不断地接受新客户。我希望它能够不断地从它所接受的所有客户那里接收信息。这段代码接受客户机,然后从客户机接收一条消息,然后发送一条消息,就是这样。我能想到的唯一一件事就是在while(true)循环中使用async receive方法,但这听起来并不正确 我稍微修改了示例,但它仍然具有相同的基本功能 public class AServer { // Thread signal. public static Man

我使用的是在这里找到的MSDN服务器示例

我的问题是,这段代码只会不断地接受新客户。我希望它能够不断地从它所接受的所有客户那里接收信息。这段代码接受客户机,然后从客户机接收一条消息,然后发送一条消息,就是这样。我能想到的唯一一件事就是在while(true)循环中使用async receive方法,但这听起来并不正确

我稍微修改了示例,但它仍然具有相同的基本功能

public class AServer
{
    // Thread signal.
    public static ManualResetEvent allDone = new ManualResetEvent(false); 
    Socket listener;
    ArrayList clients;

    public AServer(int port)
    {
        // Establish the local endpoint for the socket.
        // The DNS name of the computer
        // running the listener is "host.contoso.com".
        IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.IPv6Any, port);

        clients = new ArrayList();

        // Create a TCP/IP socket.
        listener = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
        listener.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0);
        listener.Bind(localEndPoint);
        listener.Listen(100);
    }

    public void ServerLoop(){
        while (true)
        {
            // Set the event to nonsignaled state.
            allDone.Reset();

            // Start an asynchronous socket to listen for connections.
            Console.WriteLine("Waiting for a connection...");
            listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);

            // Wait until a connection is made before continuing.
            allDone.WaitOne();
        }

    }

    public void AcceptCallback(IAsyncResult ar)
    {
        // Signal the main thread to continue.
        allDone.Set();

        // Get the socket that handles the client request.
        Socket listener = (Socket)ar.AsyncState;
        Socket handler = listener.EndAccept(ar);

        // Create the state object.
        ClientData state = new ClientData();
        state.workSocket = handler;
        clients.Add(state);

        handler.BeginReceive(state.buffer, 0, ClientData.BufferSize, 0,new AsyncCallback(ReadCallback), state);
        Console.WriteLine("we passed handler.BeginReceive");
    }

    public void ReadCallback(IAsyncResult ar)
    {
        // Retrieve the state object and the handler socket
        // from the asynchronous state object.
        ClientData data = (ClientData)ar.AsyncState;
        String buff = String.Empty;
        Socket handler = data.workSocket;

        // Read data from the client socket. 
        int bytesRead = handler.EndReceive(ar);

        if (bytesRead > 0)
        {
            // There  might be more data, so store the data received so far.
            buff = Encoding.ASCII.GetString(data.buffer, 0, bytesRead);
            ParseBuffer(buff);
            Send(handler, "1");
        }
        if (bytesRead == 0) {
            CloseConnection(handler);
        }
    }

    private bool ParseBuffer(String buff) {
        Console.WriteLine(buff);
        switch (buff[0]) { 
            case '0':

                break;
            case '1':
                break;
        }

        return true;
    }

    private static void Send(Socket handler, String data)
    {
        // Convert the string data to byte data using ASCII encoding.
        byte[] byteData = Encoding.ASCII.GetBytes(data);

        // Begin sending the data to the remote device.
        handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
    }

    private static void SendCallback(IAsyncResult ar)
    {
        // Retrieve the socket from the state object.
        Socket handler = (Socket)ar.AsyncState;

        // Complete sending the data to the remote device.
        int bytesSent = handler.EndSend(ar);
    }

    private static void CloseConnection(Socket handler)
    {
        handler.Shutdown(SocketShutdown.Both);
        handler.Close();
    }
}
当然,我的主方法只是依次调用构造函数和循环。arraylist是我为解决这个问题所做的一些尝试的结果

编辑


我一直在寻找与Select在C中提供的功能相同的功能,但显然C#可以对事件做同样的事情

在您的
ReadCallback
中,您需要再次发布异步
Receive

public void ReadCallback(IAsyncResult ar)
{
    // Retrieve the state object and the handler socket
    // from the asynchronous state object.
    ClientData data = (ClientData)ar.AsyncState;
    String buff = String.Empty;
    Socket handler = data.workSocket;

    // Read data from the client socket. 
    int bytesRead = handler.EndReceive(ar);

    if (bytesRead > 0)
    {
        // There  might be more data, so store the data received so far.
        buff = Encoding.ASCII.GetString(data.buffer, 0, bytesRead);
        ParseBuffer(buff);
        Send(handler, "1");

        // Here, you need to Receive again
        handler.BeginReceive(state.buffer, 0, ClientData.BufferSize, 0,new AsyncCallback(ReadCallback), state);
    }
    if (bytesRead == 0) {
        CloseConnection(handler);
    }
}   
这样,您将在每个套接字上接收、发送、接收、发送、接收、发送等。您需要错误处理,并且适当的服务器需要处理不完整的消息,但这是一般的想法

顺便说一句,同样,您必须在Accept回调中发布另一个异步Accept:

public void AcceptCallback(IAsyncResult ar)
{
    // Signal the main thread to continue.
    allDone.Set();

    // Get the socket that handles the client request.
    Socket listener = (Socket)ar.AsyncState;
    Socket handler = listener.EndAccept(ar);

    // Create the state object.
    ClientData state = new ClientData();
    state.workSocket = handler;
    clients.Add(state);

    handler.BeginReceive(state.buffer, 0, ClientData.BufferSize, 0,new AsyncCallback(ReadCallback), state);
    Console.WriteLine("we passed handler.BeginReceive");

    // Here, you must start a new accept:
    listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
}

听起来不错。我现在在家,所以我没有密码,但我想你知道了。