我有一个问题,我没有从连接的 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 连接正常,但接收数据时出现一些问题。它只是空白
在服务器端,您的问题是您更新了 toy byte array new byte[tcp.ReceiveBufferSize]
。你也可以做这样的事情:
using( var inputStream = new MemoryStream() )
{
tcp.GetStream().CopyTo(inputStream);
Encoding.ASCII.GetString(inputStream.ToArray());
listBox1.Items.Add(dataReceived);
...
}
请记住using
所有 IDisposable,否则您将耗尽资源。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句