TcpListener 没有收到任何数据

TcpListener is not receiving any data

我有一个问题,我没有从连接的 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 连接正常,但接收数据时出现一些问题。它只是空白

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

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

记住在所有 IDisposable 上 using,否则你将 运行 资源不足。