我已经使用TcpListener和TcpClient实现了服务器和客户端。
基本上服务器等待连接的客户端接收数据并关闭,客户端也会连接,写入和关闭。
问题是当我发送不完整的http请求时,服务器无法读取它。例如“GET / HTTP / 1.1 \ r \ n”是不完整的,因为它必须以'\ r \ n'结束两次,但如果我发送“PET / HTTP / 1.1 \ r \ n”(不是http请求)服务器读得很好。那里发生了什么?
这是我的示例代码:
static void Main()
{
var message = @"GET / HTTP/1.1
";
var encodingMessage = message.Select(Convert.ToByte).ToArray();
// SERVER
var serverThread = new Thread(() =>
{
var tcpListener = new TcpListener(IPAddress.Parse("172.20.48.37"), 23000);
tcpListener.Start();
var tcpClient = tcpListener.AcceptTcpClient();
var networkStream = tcpClient.GetStream();
var buffer = new byte[250];
var bytesCount = networkStream.Read(buffer, 0, buffer.Length);
Console.WriteLine(@"received bytes: {0}", bytesCount); // print the received bytes
networkStream.Close();
networkStream.Dispose();
tcpClient.Close();
tcpListener.Stop();
});
serverThread.Start();
Thread.Sleep(3000);
// CLIENT
var client = new TcpClient();
client.Connect(new IPEndPoint(IPAddress.Parse("172.20.48.37"), 23000));
var stream = client.GetStream();
stream.Write(encodingMessage, 0, encodingMessage.Length);
stream.Close();
stream.Dispose();
client.Close();
}