多个客户端异步连接,同步发送/接收

时间:2012-12-25 15:01:13

标签: c# sockets client-server

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

我对Async 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);
    }

1 个答案:

答案 0 :(得分:2)

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

如果您想接受多个请求,则需要在处理完请求后再次致电BeginAccept()

另见Asynchronous server socket multiple clients

修改

如果您想允许并发请求,则应在BeginAccept()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);
}