使用Socket的简单Web服务器
Socket类在System.Net.Sockets命名空间
常用的操作
Bind:绑定一个本地的终结点
Listen:进入监听状态,并设置等待队列
Accept:等待一个新连接,当连接到达时,返回一个新的socket对象。通过新的socket对象,与新连接通讯
Receive:接受字节数据,保存到一个字节数组里,并返回字节数
Send:发送响应数据
using System; using System.Net; using System.Net.Sockets; namespace WebSocket { class Program { static void Main(string[] args) { //本机的loopback环回地址,即127.0.0.1 IPAddress address = IPAddress.Loopback; //初始化地址和端口 IPEndPoint endPoint = new IPEndPoint(address, 59152); //创建socket Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind(endPoint); socket.Listen(10); Console.WriteLine("Listening Port:{0}",endPoint.Port); while (true) { //为连接创建新的socket,开始监听 Socket client = socket.Accept(); //接受数据的数组 byte[] buffer = new byte[4096]; //接受数据 int length = client.Receive(buffer, SocketFlags.None); //utf8 编码 System.Text.Encoding utf8 = System.Text.Encoding.UTF8; //请求的数据 string requestStr = utf8.GetString(buffer, 0, length); Console.WriteLine("Request String:{0}",requestStr); //回应主体、头部等.. string responseBody = "<html><head></head><body><h1>Hello</h1></body></html>"; byte[] responseBodyBytes = utf8.GetBytes(responseBody); client.Send(responseBodyBytes); client.Close(); if (Console.KeyAvailable) { break; } } socket.Close(); } } }
运行后,在浏览器输入http://localhost:59152/