我想在套接字编程中使用TcpListener读取大于1024字节的数据。当我尝试从网络流中读取数据时,它会分成多个部分。
const int port = 1200;
this._ip = IPAddress.Parse("192.168.0.12");
this._server = new TcpListener(this._ip, port);
this._server.Start();
while (true)
{
var client = this._server.AcceptTcpClient();
var remoteEndPoint = (IPEndPoint)client.Client.RemoteEndPoint;
Console.WriteLine(@"Connected");
this._publicIp = "";
if (remoteEndPoint != null)
{
this._publicIp = remoteEndPoint.Address.ToString();
}
this._stream = client.GetStream();
int i = _stream.Read(_bytes, 0, _bytes.Length);
string str = Encoding.ASCII.GetString(_bytes, 0, i);
client.Close();
}
int i = _stream.Read(_bytes, 0, _bytes.Length);
string str = Encoding.ASCII.GetString(_bytes, 0, i);
答案 0 :(得分:0)
尝试一下,这与使用SendReceiveBuffer有关
TcpListener tcpListener = new TcpListener(IPAddress.Any, serverTCPPort);
tcpListener.Start();
string received = "";
while (true)
{
tcpClient = tcpListener.AcceptTcpClient();
stream = tcpClient.GetStream();
reader = new StreamReader(stream);
writer = new StreamWriter(stream);
writer.NewLine = "\r\n";
writer.AutoFlush = true;
byte[] bytes = new byte[tcpClient.SendBufferSize];
int recv = 0;
while (true)
{
recv = stream.Read(bytes, 0, tcpClient.SendBufferSize);
received += System.Text.Encoding.ASCII.GetString(bytes, 0, recv);
if (received.EndsWith("\n\n"))
{
break;
}
}
}