<分区>
作为 C# 和 C# 网络编程的“新手”,我尝试使用 TCPClient 和 TCPListener 在 C# 中进行简单的聊天,我设法将数据从客户端发送到服务器,但是如果我添加第二个客户端,服务器不会读取他的数据和我有第二个问题我无法弄清楚如何使用 TCPListener 将数据从服务器发送到客户端。
服务器:
while (true)
{
Socket client = Server.AcceptSocket();
Console.WriteLine("Connection accepted from " + client.RemoteEndPoint);
count += 1;
string msg;
byte[] buf = new byte[1024];
client.Receive(buf);
msg = Encoding.UTF8.GetString(buf);
Console.WriteLine("Received... " + msg + "");
}
}
客户:
while (true)
{
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String msg = Console.ReadLine();
Stream stm = tcpClient.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
byte[] send = asen.GetBytes(msg);
Console.WriteLine("Transmitting.....");
stm.Write(send, 0, send.Length);
if (msg == "/Q"){
tcpClient.Close();
Environment.Exit(0);
}
}
如果您在我的代码中看到任何荒谬/错误,请告诉我,我是来学习的!
谢谢