C# 具有多个客户端的 TCP 服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19218589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:25:36  来源:igfitidea点击:

TCP server with multiple Clients

c#socketstcptcpserver

提问by

I am working on TCP server/client application.

我正在开发 TCP 服务器/客户端应用程序。

My question is:

我的问题是:

My server application starts a new thread and blocks it until connection is accepted the listenforClient method

我的服务器应用程序启动一个新线程并阻止它直到连接被接受listenforClient 方法

But how can I manage the connections when multiple Clients are connected to my server and they request different things at the same time how can i manage that client 1 gets info its need and same for client 2.

但是,当多个客户端连接到我的服务器并且它们同时请求不同的东西时,我如何管理连接,我如何管理客户端 1 获取其需要的信息,客户端 2 的信息也是如此。

It's multithreaded, so multiple Clients can connect but how can i process the request. I don't want to put everything in 1 method what than would.

它是多线程的,因此可以连接多个客户端,但我如何处理请求。我不想把所有东西都放在 1 种方法中。

Thanks in Advance

提前致谢

private void serverstart()
    {
        this.tcplistener = new TcpListener(IPAddress.Any, 49151);
        this.listenThread = new Thread(new ThreadStart(ListenForClients));
        this.listenThread.Start();
    }

    private void ListenForClients()
    {
        this.tcplistener.Start();

        while (true)
        {
            //blocks until a client has connected to the server
            TcpClient client = this.tcplistener.AcceptTcpClient();


            // here was first an message that send hello client
            //
            ///////////////////////////////////////////////////

            //create a thread to handle communication
            //with connected client
            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));

            clientThread.Start(client);
        }
    }

    private void HandleClientComm(object client)
    {
        TcpClient tcpClient = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();

        byte[] message = new byte[4096];
        int bytesRead;

        while (true)
        {
            bytesRead = 0;

            try
            {
                //blocks until a client sends a message
                bytesRead = clientStream.Read(message, 0, 4096);
            }
            catch
            {
                //a socket error has occured
                break;
            }

            if (bytesRead == 0)
            {
                //the client has disconnected from the server
                break;
            }

            //message has successfully been received
            ASCIIEncoding encoder = new ASCIIEncoding();

            bufferincmessage = encoder.GetString(message, 0, bytesRead);


            if (System.Text.RegularExpressions.Regex.IsMatch(bufferincmessage, Properties.Settings.Default.REQLogin, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
            {
                bufferincmessageresult = bufferincmessage.Split('^');
                nickname_Cl = bufferincmessageresult[1];
                password_Cl = bufferincmessageresult[2];
                getuserdata_db();
                login();

                byte[] buffer = encoder.GetBytes(inlogmessage);

                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();
            }


        }
    }

回答by zaynyatyi

Your client will be dispatched in different threads, so they will not intersect. You just need to add something like "DispatchMethod" where your messages will be processed.

您的客户端将在不同的线程中分派,因此它们不会相交。您只需要添加诸如“DispatchMethod”之类的内容即可处理您的消息。

using System.Text.RegularExpressions;
...

if (Regex.IsMatch(bufferincmessage, Properties.Settings.Default.REQLogin, RegexOptions.IgnoreCase))
{
    ...
}
else if (Regex.IsMatch(bufferincmessage, /*some of your command1*/, RegexOptions.IgnoreCase))
{
    ...
}
else if (Regex.IsMatch(bufferincmessage, /*some of your command1*/, RegexOptions.IgnoreCase))
{
    ...
}