【问题标题】:Receiving messages as TcpClient作为 TcpClient 接收消息
【发布时间】:2015-09-13 16:13:36
【问题描述】:

我一直在关注本教程“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)并获取流(如上)。然后等待消息并对其进行处理。我不能让客户端在发送消息后立即从服务器接收消息的原因是因为客户端将向服务器发送消息,然后该消息将广播给所有连接的客户端。所以每个客户端都需要“监听”来自服务器的消息。

【问题讨论】:

  • 本教程确实展示了如何创建侦听器,您的评论在哪里,它们会显示一个循环来读取传入的消息。 (并返回一个字节数组,需要根据发送的数据读入正确的格式)
  • 啊...我以为这仅适用于服务器端,而不是客户端...好的,现在尝试复制它:)

标签: c# tcp client-server tcpclient


【解决方案1】:

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

后,可以将 byte 方法替换为

希望这会有所帮助!

**PS:如果您希望在 c# 中使用网络类获得更通用的编码体验,我个人建议考虑使用套接字,因为它是 tcpclient 和 tcplistener 诞生的主要类。

【讨论】:

  • 您好,谢谢您的回答!非常抱歉我迟到的回复。我可以在问题中添加一个问题并询问“从服务器接收数据”代码应该去哪里。客户端如何“等待”接收数据?我问的原因是因为服务器正在向其他客户端广播消息,所以回复不会只发生在发送原始消息的客户端
  • 好的,那么您可能必须创建一个方法,将相同的消息发送到每个单独的连接。 Tcp 是一对一的连接,而例如 UDP(尽管如果您希望一切都从点 a 到 b 的安全性和可靠性较低)广播消息要容易得多。据我所知,没有办法通过每个连接广播 tcp wirhout 循环
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多