C# 作为TcpClient接收消息
我一直在遵循本教程“设置一个可以发送和接收消息并连接多个客户端的迷你服务器” 一切都很好。。但不幸的是,本教程中缺少的一件事是客户端如何设置侦听器来侦听服务器 我只有这么多:C# 作为TcpClient接收消息,c#,tcp,client-server,tcpclient,C#,Tcp,Client Server,Tcpclient,我一直在遵循本教程“设置一个可以发送和接收消息并连接多个客户端的迷你服务器” 一切都很好。。但不幸的是,本教程中缺少的一件事是客户端如何设置侦听器来侦听服务器 我只有这么多: public void SetupReceiver() { TcpClient tcpClient = new TcpClient(this.Host, this.Port); NetworkStream networkStream = tcpClient.GetStream(); /
public void SetupReceiver()
{
TcpClient tcpClient = new TcpClient(this.Host, this.Port);
NetworkStream networkStream = tcpClient.GetStream();
// What next! :( or is this already wrong...
}
就我所能想象的。。我需要连接到服务器(作为TcpClient)并获取流(如上所述)。然后等待消息并对其进行处理。我不能让客户端在发送消息后立即从服务器接收回消息的原因是,客户端将向服务器发送消息,然后该消息将广播到所有连接的客户端。因此,每个客户机都需要“监听”来自服务器的消息。TCPclient类拥有必要的资源来启用与服务器之间的连接、发送和接收数据,TCPListener类本质上就是服务器 遵循msdn页面中为TCPclient提供的一般示例,也可用于TCPListener(我的一般解释基于此!) 第一部分是向服务器发送数据:
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length); //(**This is to send data using the byte method**)
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length); //(**This receives the data using the byte method**)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); //(**This converts it to string**)
以下部分用于从服务器接收数据:
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length); //(**This is to send data using the byte method**)
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length); //(**This receives the data using the byte method**)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); //(**This converts it to string**)
一旦字节方法链接到网络流,它们就可以被流读取器和流编写器替换
希望这有帮助
**PS:如果您希望在c#中的网络类中获得更全面的编码体验,我个人建议您考虑使用Socket,因为它是tcpclient和tcplistener诞生的主要类。本教程确实展示了如何创建侦听器,您的评论就在这里,它们显示一个将读取传入消息的循环。(并返回一个字节数组,需要根据发送的数据将其读入正确的格式)啊。。。我以为那只是服务器端的,不是客户端的。。。好的,现在就试着复制一下:)嗨,谢谢你的回答!很抱歉我迟了回复。请允许我在问题中添加一个问题,并询问“从服务器接收数据”代码应该放在哪里。客户端将如何“等待”接收数据?我询问的原因是,服务器正在向其他客户端广播消息,因此回复不会只出现在发送原始消息的客户端上。确定后,您可能必须创建一个方法,将相同的消息发送到每个单独的连接。Tcp是一对一连接,而UDP(例如,如果您希望从a点到b点的所有信息都能得到,则安全性和可靠性较低)则更容易广播消息。据我所知,没有一种方法不通过每个连接循环来广播tcp