1

我是 C#、OOP、网络和 TCP/IP 套接字的新手...

我对异步 TCP/IP 套接字通信的使用有误解。我正在尝试创建一个等待多个客户端的服务器,并且每次客户端连接时,它都会显示类似“用户 192.168.1.105:2421 已加入”的内容

我认为当您使用 BeginAccept() 时,将创建一个新线程……每当有新用户连接时,它将负责与该特定客户端的通信。但是,以下代码块......并且不显示第二个客户端的消息。

我应该改变什么,以便为每个连接的客户端我有一个单独的线程来处理执行?

class Server
{
    Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    //constructor 
    public Server()
    {
        listener.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.100"), 9050));
        listener.Listen(10);
        listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
        Console.Write("Server Running...\r\n");
    }

    public void OnConnectRequest(IAsyncResult ar)
    {
        Socket listener = (Socket)ar.AsyncState;
        NewConnection(listener.EndAccept(ar));
        listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
    }

    //send a string message over a TCP socket 
    public void sendMSG(string msg,Socket socket)
    {
     //some code which sends data according to my protocol
    }

    public byte[] receiveMSG(ref Socket socket)
    {
     //some code which receives data according to my protocol
    }


    //function called whenever a NEW CLIENT is connected
    public void NewConnection(Socket sockClient)
    {
        Console.WriteLine("user {0} has joined",sockClient.RemoteEndPoint);
        byte[] msg = new byte[20];
        sockClient.Receive(msg);
    }
4

1 回答 1

2

BeginAccept()接受一个请求,因此您的异步回调只会为第一个请求调用一次。这是标准的 C# 异步模式。

如果您想接受多个请求,您需要BeginAccept()在处理完请求后再次调用。

另请参阅异步服务器套接字多个客户端

编辑:

如果您想允许并发请求,您应该在andBeginAccept()之间调用:EndAccept()NewConnection()

public void OnConnectRequest(IAsyncResult ar)
{
    Socket listener = (Socket)ar.AsyncState;
    Socket accepted = listener.EndAccept(ar);
    listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
    NewConnection(accepted);
}
于 2012-12-25T15:15:48.080 回答