[英]TcpListener is not receiving any data
i have an issue where im not receiving any bytes from the connected TcpClient! 我有一个问题,即即时通讯没有从连接的TcpClient接收任何字节!
Server: (i attempt to add the received message into a listbox, but nothing comes out. 服务器:(我尝试将接收到的消息添加到列表框中,但是什么也没有出现。
//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
}
Client: 客户:
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 The connection works, but theres some issues receiving data. I连接正常,但是接收数据时出现一些问题。 it just comes out blank
它只是一片空白
On serverside, your problem is that you renew toy byte array new byte[tcp.ReceiveBufferSize]
. 在服务器端,您的问题是您更新了玩具字节数组
new byte[tcp.ReceiveBufferSize]
。 You could also do something like this: 您还可以执行以下操作:
using( var inputStream = new MemoryStream() )
{
tcp.GetStream().CopyTo(inputStream);
Encoding.ASCII.GetString(inputStream.ToArray());
listBox1.Items.Add(dataReceived);
...
}
Remember using
on all IDisposable's, else you will run out of resources. 记得
using
所有的IDisposable的,否则你会耗尽资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.