web 编写遵循的核心协议就是http/tcp 协议。而这个核心的内容是就Socket编程。
Socket 是点对点的通讯模式,是全双工的。是靠IP地址进行寻址访问的。
根据设计又几种模式: 点对点 (适合两者之间大文件的传输) 服务器模式(聊天,webapi等)
这里主要讨论: 服务器模式
Socket 编程需要引用
using System.Net;
using System.Net.Sockets;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 static void Main(string[] args) 2 { 3 Console.WriteLine("程序开始:"); 4 Socket sk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 5 sk.Bind(new IPEndPoint(IPAddress.Any, 8044)); 6 sk.Listen(10); 7 while (true) 8 { 9 Socket st = sk.Accept(); 10 string result = ""; 11 int buffSize = 1; 12 byte[] buffer = new byte[1024]; 13 while (buffSize > 0) 14 { 15 buffSize = st.Receive(buffer); 16 result += Encoding.UTF8.GetString(buffer, 0, buffSize); 17 if (buffSize < 1024) 18 { 19 buffSize = 0; 20 } 21 } 22 Console.WriteLine(result); 23 if (result.Length > 0) 24 { 25 buffSize = 1; 26 string statusline = "HTTP/1.1 200 OK "; //状态行 27 byte[] statusline_to_bytes = Encoding.UTF8.GetBytes(statusline); 28 29 string content = 30 "<html>" + 31 "<head>" + 32 "<title>socket webServer -- Login</title>" + 33 "</head>" + 34 "<body>" + 35 "<div style="text-align:center">" + 36 "欢迎您!" + "" + ",今天是 " + DateTime.Now.ToLongDateString() + 37 "</div>" + 38 "</body>" + 39 "</html>"; //内容 40 41 42 byte[] content_to_bytes = buffer; 43 44 string header = string.Format("Content-Type:text/html;charset=UTF-8 Content-Length:{0} ", content_to_bytes.Length); 45 byte[] header_to_bytes = Encoding.UTF8.GetBytes(header); //应答头 46 47 48 st.Send(statusline_to_bytes); //发送状态行 49 st.Send(header_to_bytes); //发送应答头 50 st.Send(new byte[] { (byte)' ', (byte)' ' }); //发送空行 51 st.Send(Encoding.UTF8.GetBytes(content)); //发送正文(html) 52 st.Close(); 53 54 } 55 56 } 57 }