简体   繁体   English

我是否需要多个流和TCP客户端才能在C#中创建聊天应用程序

[英]Do i need multiple streams and TCP clients to make a chat application in c#

i am using the following code on server for communication between the server and client 我在服务器上使用以下代码在服务器和客户端之间进行通信

TcpListener server = new TcpListener(IPAddress.Any, 9999);
server.Start();

Console.WriteLine("Waiting for client connections");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Client request accepted");

NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
StreamWriter writer = new StreamWriter(stream);

Now this code works fine for connecting a single client, But what tweaking i need to do in order allow more than one client to connect to my server ? 现在,此代码可以很好地用于连接单个客户端,但是为了允许多个客户端连接到我的服务器,我需要做哪些调整?

Do i need a new TCP listener on a new port for each client ? 我是否需要为每个客户端在新端口上使用新的TCP侦听器? Do i need Multiple TCP clients and streams ? 我需要多个TCP客户端和流吗? A brief guide on making this code be able to handle >1 clients would be appreciated. 一个简短的指南,使该代码能够处理> 1个客户端,将不胜感激。

You would want to put the server.AcceptTcpClient() in a loop as each time a new client connects it will return another TcpClient . 您可能希望将server.AcceptTcpClient()置于循环中,因为每次新客户端连接时,它将返回另一个TcpClient You can see a simple example of this in the MSDN documentation here: http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.accepttcpclient.aspx 您可以在以下MSDN文档中看到一个简单的示例:http://msdn.microsoft.com/zh-cn/library/system.net.sockets.tcplistener.accepttcpclient.aspx

You would still have one listener ... but each "accept" should spawn a different thread or task. 您仍然会有一个侦听器...但是每个“接受”应该产生不同的线程或任务。 The new thread would then create it's own stream. 然后,新线程将创建自己的流。

Do something like this on server side: 在服务器端执行以下操作:

            while (true)
            {
              if (server.Pending()) // if there are any pending connections to server
                  {
                      //accept tcpClient and perform further operations.
                      //create a different thread per client
                   }
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM