作为TcpClient接收消息

4
我一直在学习关于搭建迷你服务器,可以发送和接收消息并且连接多个客户端的教程"http://tech.pro/tutorial/704/csharp-tutorial-simple-threaded-tcp-server"。
一切运作良好,但遗憾的是这个教程缺少了一个重要部分,就是客户端如何设置监听来监听服务器。目前我只有这么多内容:
public void SetupReceiver()
{
      TcpClient tcpClient = new TcpClient(this.Host, this.Port);
      NetworkStream networkStream = tcpClient.GetStream();

      // What next! :( or is this already wrong...
}

据我所想,我需要连接到服务器(作为TcpClient)并获取流(如上所述)。然后等待消息并对其进行处理。我不能让客户端在发送一条消息后立即从服务器收到一条消息的原因是,客户端将向服务器发送一条消息,然后该消息将广播到所有连接的客户端。因此,每个客户端都需要“监听”来自服务器的消息。


1
该教程展示了如何创建监听器,在您的评论所在位置,他们展示了一个循环,将读取传入的消息。(并返回一个字节数组,需要根据发送的数据类型读取到正确的格式中) - Cyral
啊...我以为那只是针对服务器端,而不是客户端...好的,现在要尝试复制它 :) - Zephni
1个回答

7
TCPclient类具有必要的资源,以启用连接、发送和接收来自服务器的数据,而TCPListener类则本质上是服务器。
按照msdn页面提供的通用示例,可以使用TCPclient类,也可以用于TCPListener类(我的概括性解释基于此!)。

https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient%28v=vs.110%29.aspx

第一部分是将数据发送到服务器:

// 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**)

字节方法可以用streamreaderstreamwriter替代,一旦它们链接到networkstream
希望这可以帮助!
** PS:如果您想在C#中使用网络类获得更多功能丰富的编程体验,我个人建议研究使用套接字,因为它是从中诞生tcpclient和tcplistener的主要类。

非常感谢您的回答!非常抱歉我回复晚了。我能否在问题中添加一个问题,并询问“接收来自服务器的数据”的代码应该放在哪里?客户端如何“等待”接收数据?我之所以这样问,是因为服务器正在向其他客户端广播消息,因此回复不仅会发生在发送原始消息的客户端上。 - Zephni
好的,那么您可能需要创建一个方法,将相同的消息发送到每个单独的连接。TCP是一对一的连接,而UDP例如(虽然不太安全且不太可靠,如果您希望所有内容从点A到点B)则更容易广播消息。据我所知,没有一种方法可以在不循环遍历每个连接的情况下广播TCP。 - Viralwarrior012

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接