0
我想在無限循環中讀寫一個套接字。套接字讀寫一個循環
當我在第一個循環中寫入流的請求時,我可以立即讀取響應。
但對於其他迴路networkStream.DataAvailable
總是假。
如何連續讀寫套接字。
static void ReadWriteSocket()
{
string requestString = "GET /WebApplication.UI HTTP/1.1 \r\n" +
"Host: 172.17.107.30 \r\n" +
"Connection:close \r\n\r\n";
client = new TcpClient();
client.Connect(new IPEndPoint(IPAddress.Parse("172.17.107.30"), 80));
byte[] buffer = System.Text.Encoding.Default.GetBytes(requestString);
byte[] readBuffer = new byte[1024];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
var networkStream = client.GetStream();
networkStream.Write(buffer, 0, buffer.Length);
networkStream.Flush();
int recievedByte = 0;
if (networkStream.DataAvailable)
{
while ((recievedByte = networkStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
ms.Write(readBuffer, 0, recievedByte);
}
}
Console.WriteLine(System.Text.Encoding.Default.GetString(ms.ToArray()));
}
}
}