所以我正在使用TCP协议进行C#聊天,我想不通如何使服务器将客户端接收到的数据发送给与之连接的所有客户端。因此,我尝试将所有客户端放入一个arraylist中,并使用“ foreach”向其发送服务器接收的数据(如本主题中所述),但失败了。为了发送和接收数据,我使用Streams(StreamWriter / StreamReader)。每个客户端由服务器在不同的线程中处理。
问题:如何将数据同时发送到所有客户端?
服务器 :
static void LoopClients()
{
while (running)
{
TcpClient newClient = server.AcceptTcpClient();
arrClient.add(newClient)
Console.WriteLine("Connection accepted from " + ((IPEndPoint)newClient.Client.RemoteEndPoint).Address);
Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
t.Start(newClient);
}
}
static void HandleClient(object obj)
{
TcpClient client = (TcpClient)obj;
StreamWriter Writer = new StreamWriter(client.GetStream(), Encoding.ASCII);
StreamReader Reader = new StreamReader(client.GetStream(), Encoding.ASCII);
Boolean ClientConnected = true;
String Data = null;
var LEP = client.Client.RemoteEndPoint as IPEndPoint;
var LAD = LEP.Address;
while (ClientConnected)
{
Data = Reader.ReadLine();
Console.WriteLine(""+ LAD + " : " + Data);
Writer.WriteLine(LAD+" : "+Data+"");
Writer.Flush();
}
}
谢谢你 !
繁华开满天机
相关分类