【发布时间】:2018-09-18 02:24:49
【问题描述】:
作为 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);
}
}
如果您在我的代码中发现任何荒谬/错误,请告诉我我在这里学习!
谢谢
【问题讨论】:
-
我认为这不是关于通过 TCP 发送 JSON 序列化数据的问题的重复。尽管该问题包含有关 TCP 通信的完整示例,但可以通过修复代码中可见的 OP 的误解和错误来回答此问题。
-
现在我想起来了,这个问题适合 CodeReview,但是将它标记为版主发现的第一个 TCP 相关问题的副本是错误的 imo。我建议 OP 提出上诉。
标签: c# .net tcpclient tcp-ip tcplistener