如何在TCP C#套接字服务器中处理多个活动连接?

时间:2016-09-22 16:33:28

标签: c# sockets tcp

到目前为止,我的套接字服务器非常简单:

        public static void listen()
    {
        TcpListener server = null;
        IPAddress address = IPAddress.Parse("127.0.0.1");
        try
        {
            server = TcpListener.Create(5683);
            server.Start();

        }
        catch (Exception e)
        {
            Console.WriteLine(e.StackTrace);
        }


        while (true)
        {
            Thread.Sleep(10);
            TcpClient client = server.AcceptTcpClient();
            Console.WriteLine("Accepted Client");

            Thread thread = new Thread (new ParameterizedThreadStart(SwordsServer.ClientHandler));
            thread.IsBackground = true;
            thread.Start(client);
        }
    }

    public static void ClientHandler(object c)
    {
        TcpClient client = (TcpClient)c;
        NetworkStream netstream = client.GetStream();
        bool connected = true;
        while (connected)
        {
            Thread.Sleep(10);
            try
            {
                byte[] bytes = new byte[client.ReceiveBufferSize];                   
                netstream.Read(bytes, 0, bytes.Length);
                Console.WriteLine("got data");
                netstream.Write(bytes, 0, bytes.Length);

            }
            catch (Exception e)
            {
                connected = false;
                Console.WriteLine(e);
                Console.WriteLine(e.StackTrace);
            }
        }
    }

我的问题是,在概念层面上,您如何密切关注每个唯一client并将更新从其他线程发送到特定客户端?

例如,如果我有特定客户的数据,我该如何联系该客户端而不是广播它?或者,如果客户不再连接,我该怎么说?

提前感谢您的任何帮助!

1 个答案:

答案 0 :(得分:1)

您接受多个连接的实现会创建匿名客户端,这意味着在超过1个连接之后您将无法识别正确的客户端。如果识别是问题,那么你可以做一件事,让客户端向服务器发送一个标识符,如" Client1"。创建一个Dictionary并在你的方法ClientHandler()中,从客户端读取标识符并在字典中添加TCPClient对象。

因此修改后的代码将是这样的:

 Dictionary<string, TCPClient> dictionary = new Dictionary<string, TCPClient>();


 public static void ClientHandler(object c)
    {
        TcpClient client = (TcpClient)c;
        NetworkStream netstream = client.GetStream();
        bool connected = true;
        while (connected)
        {
            Thread.Sleep(10);
            try
            {
                byte[] bytes = new byte[client.ReceiveBufferSize];

                //read the identifier from client
                netstream.Read(bytes, 0, bytes.Length);

                String id = System.Text.Encoding.UTF8.GetString(bytes);

                //add the entry in the dictionary
                dictionary.Add(id, client);
                Console.WriteLine("got data");
                netstream.Write(bytes, 0, bytes.Length);

            }
            catch (Exception e)
            {
                connected = false;
                Console.WriteLine(e);
                Console.WriteLine(e.StackTrace);
            }
        }
    }

请注意:您的应用程序应足够智能,以动态决定应将更新发送到哪个客户端。