标签:
//读取浏览器发过来的内容
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));//程序要监听8080端口,如果别的程序已经占了这个端口,那程序就会抛异常
serverSocket.Listen(10);//启动监听10个用户
//进行死循环是为了可以多个请求
while (true)
{
Console.WriteLine("等着请求");
Socket socket = serverSocket.Accept();//等待有人请求,返回上一次Socket的通讯通道
Console.WriteLine("来了请求了");
using (NetworkStream stream = new NetworkStream(socket))
using (StreamReader reader = new StreamReader(stream))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
if (line.Length <= 0)
{
break;//遇到空行,请求结束,不用再等了
//如果不break,就一直卡在ReadLine()等着浏览器发出的数据
}
}
}
//返回给浏览器的内容
using (NetworkStream stream = new NetworkStream(socket))
using (StreamWriter write = new StreamWriter(stream))
{
write.WriteLine("HTTP/1.1 200 OK");
write.WriteLine();
write.WriteLine("welcome to china");
}
socket.Disconnect(false);//断开通讯
}
启动C#程序,打开浏览器,输入127.0.0.1:8080
执行结果:
请求报文头内容,在浏览器上面按F12,刷新页面,点Network可以看到如下内容:
返回内容:
标签:
原文地址:http://www.cnblogs.com/genesis/p/4657153.html