【问题标题】:TcpListener is not receiving any dataTcpListener 没有收到任何数据
【发布时间】:2017-11-08 04:41:03
【问题描述】:

我有一个问题,我没有从连接的 TcpClient 接收任何字节!

服务器:(我尝试将收到的消息添加到列表框中,但没有任何结果。

   //tl is a TcpListener
   //I set this up in a 500 milisecond loop. No worries about that.
   if (tl.Pending())
   {
     TcpClient tcp = tl.AcceptTcpClient();
     var s = tcp.GetStream();
     int bytesRead = s.Read(new byte[tcp.ReceiveBufferSize], 0, 
     tcp.ReceiveBufferSize);
     string dataReceived = Encoding.ASCII.GetString(new 
     byte[tcp.ReceiveBufferSize], 0, bytesRead);
     listBox1.Items.Add(dataReceived);
     tcp.Close();
     oac++; //Overall connection count
     label3.Text = "Overall Connections: " + oac; //logging connections
   }

客户:

 void Send(){
    TcpClient c = new TcpClient(Im not including my ip., 4444);
    System.IO.StreamWriter w = new System.IO.StreamWriter(c.GetStream());
    byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes($"Username: \"
    {textBox1.Text}\" | Password: \"{textBox2.Text}\"");
    NetworkStream nwStream = c.GetStream();
    nwStream.Write(bytesToSend, 0, bytesToSend.Length);
    nwStream.Flush();
  }

I 连接正常,但接收数据时出现问题。它只是空白

【问题讨论】:

  • 您使用填充为 0 的字节数组(新字节 [...])创建 dataReceived 字符串,因此它始终为空。然后您将数据从套接字读取到另一个立即丢弃的字节数组

标签: c# byte tcplistener


【解决方案1】:

在服务器端,您的问题是您更新了玩具字节数组new byte[tcp.ReceiveBufferSize]。你也可以这样做:

using( var inputStream = new MemoryStream() )
{
  tcp.GetStream().CopyTo(inputStream);
  Encoding.ASCII.GetString(inputStream.ToArray());
  listBox1.Items.Add(dataReceived);
  ...
}

在所有 IDisposable 上记住 using,否则您将耗尽资源。

【讨论】:

  • System.IO.IOException: '无法从传输连接读取数据:现有连接被远程主机强行关闭。'呃,我在 tcp.GetStream().CopyTo(inputStream); 得到这个错误;
  • 关闭客户端了吗?
  • 最好是在客户端序列化一个对象,在服务器端反序列化。
  • 我没有关闭客户端客户端。
猜你喜欢
  • 2020-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-16
相关资源
最近更新 更多