我正在尝试开发一个基于C#的GUI程序,以便从单个服务器上的多个TCP客户端接收数据。所有客户端都应该监听服务器上的相同端口,服务器接受来自多个客户端的数据,划分接收数据并将其显示在GUI中。
我尝试了这个基于控制台的程序,以便从服务器端口4000上的多个客户端接收数据。但我无法连接到客户端。对于使用特定IP地址和端口绑定的单个客户端,其工作正常。它只是等待多个客户端,并且不接收来自客户端的数据。你能告诉我如何解决这个问题的具体解决方案吗? 这是我的代码:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class ThreadedTcpSrvr
{
private TcpListener client;
public ThreadedTcpSrvr()
{
client = new TcpListener(4000);
client.Start();
while (true)
{
while (!client.Pending())
{
Thread.Sleep(100);
}
ConnectionThread newconnection = new ConnectionThread();
newconnection.threadListener = this.client;
Thread newthread = new Thread(new
ThreadStart(newconnection.HandleConnection));
newthread.Start();}
}
public static void Main()
{
ThreadedTcpSrvr server = new ThreadedTcpSrvr();
}
}
class ConnectionThread
{
public TcpListener threadListener;
private static int connections = 0;
public void HandleConnection()
{
int recv;
byte[] data = new byte[1024];
TcpClient client = threadListener.AcceptTcpClient();
NetworkStream ns = client.GetStream();
connections++;
Console.WriteLine("New client accepted: {0} active connections",
connections);
string welcome = "Welcome to the Server";
data = Encoding.ASCII.GetBytes(welcome);
ns.Write(data, 0, data.Length);
while (true)
{
data = new byte[1024];
recv = ns.Read(data, 0, data.Length);
if (recv == 0)
break;
ns.Write(data, 0, recv);
}
ns.Close();
client.Close();
connections--;
Console.WriteLine("Client disconnected: {0} active connections",
connections); }
}
P.S。我试图通过wireshark捕获数据,我能够捕获数据。