Socekt
HttpListener httplisten = new HttpListener();
IPAddress ip =IPAddress.Loopback;
IPEndPoint ipoint = new IPEndPoint(ip, 80);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ipoint);
socket.Listen(10);
Console.WriteLine("开始监听,端口号:{0}", ipoint.Port);
while (true)
{
Socket client = socket.Accept(); //监视端口,没有请求时一直阻塞。
Console.WriteLine(client.RemoteEndPoint);
byte[] buffer = new byte[4096];
int lenght = client.Receive(buffer,4096,SocketFlags.None);
Encoding encoding = Encoding.UTF8;
string requestString = encoding.GetString(buffer, 0, lenght);
Console.WriteLine(requestString);
string statusLine = "HTTP/1.1 200 OK\r\n";
byte[] statusBuffer = encoding.GetBytes(statusLine);
string responseBody = "<html><head></head><title>Test</title></head><body><h1>Hello Word!!</h1></body></html>";
byte[] responseBodyBytes = encoding.GetBytes(responseBody);
string responseHeader = string.Format("Content-Type:text/html;charset=UTF-8\r\nContent-Length:{0}\r\n", responseBody.Length);
byte[] responseHeaderBytes = encoding.GetBytes(responseHeader);
byte[] all = statusBuffer.Concat(responseHeaderBytes).Concat(new byte[] { 13, 10 }).Concat(responseBodyBytes).ToArray();
Console.WriteLine(encoding.GetString(all));
client.Send(all);//模拟服务器端发送
//client.Send(statusBuffer);
//client.Send(responseHeaderBytes);
//client.Send(new byte[] { 13,10});
//client.Send(responseBodyBytes);
//client.Close();
if (Console.KeyAvailable)
break;
}
socket.Close();
编辑器加载中...