为什么不读取 NetworkStream 中的数据? .net 客户端
Why data from NetworkStream do not read? .net TcpClient
我有客户端层和服务器层。客户端发送转换为字节数组整数变量。
我正在使用 TcpClient 和 TcpListener,并使用 NetworkStream 写入和读取数据。出于某种原因,服务器不从 NetworkStream 读取数据,尽管我使用了这个问题的建议:How to get all data from NetworkStream
客户端层:
TcpClient sender1 = new TcpClient();
sender1.Connect(ip, port);
using (NetworkStream stream1 = client.GetStream())
{
int isCorrect = 1;
byte[] data = BitConverter.GetBytes(isCorrect);
stream1.Write(data, 0, data.Length);
}
sender1.Close();
服务器层
TcpListener server = new TcpListener(IPAddress.Parse(ip), serverPort);
server.Start();
while (true)
{
TcpClient enterWaiter = server.AcceptTcpClient();
using (NetworkStream stream1 = enterWaiter.GetStream())
{
byte[] buffer = new byte[4];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = stream1.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
Console.WriteLine($"{ms.ToArray()}");
}
}
server.Stop();
break;
}
这是因为您在接收数据之前关闭服务器,移动或删除Server.Stop和断行,例如:
TcpListener server = new TcpListener(IPAddress.Parse(ip), serverPort);
server.Start();
while (true)
{
TcpClient enterWaiter = server.AcceptTcpClient();
using (NetworkStream stream1 = enterWaiter.GetStream())
{
byte[] buffer = new byte[4];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = stream1.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
Console.WriteLine($"{ms.ToArray()}");
}
}
//server.Stop(); <-- (Re)move
//break; <-- (Re)move
}
我有客户端层和服务器层。客户端发送转换为字节数组整数变量。 我正在使用 TcpClient 和 TcpListener,并使用 NetworkStream 写入和读取数据。出于某种原因,服务器不从 NetworkStream 读取数据,尽管我使用了这个问题的建议:How to get all data from NetworkStream
客户端层:
TcpClient sender1 = new TcpClient();
sender1.Connect(ip, port);
using (NetworkStream stream1 = client.GetStream())
{
int isCorrect = 1;
byte[] data = BitConverter.GetBytes(isCorrect);
stream1.Write(data, 0, data.Length);
}
sender1.Close();
服务器层
TcpListener server = new TcpListener(IPAddress.Parse(ip), serverPort);
server.Start();
while (true)
{
TcpClient enterWaiter = server.AcceptTcpClient();
using (NetworkStream stream1 = enterWaiter.GetStream())
{
byte[] buffer = new byte[4];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = stream1.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
Console.WriteLine($"{ms.ToArray()}");
}
}
server.Stop();
break;
}
这是因为您在接收数据之前关闭服务器,移动或删除Server.Stop和断行,例如:
TcpListener server = new TcpListener(IPAddress.Parse(ip), serverPort);
server.Start();
while (true)
{
TcpClient enterWaiter = server.AcceptTcpClient();
using (NetworkStream stream1 = enterWaiter.GetStream())
{
byte[] buffer = new byte[4];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = stream1.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
Console.WriteLine($"{ms.ToArray()}");
}
}
//server.Stop(); <-- (Re)move
//break; <-- (Re)move
}