模拟.net Core ---- http/tcp 通讯-- 服务器模式

web 编写遵循的核心协议就是http/tcp 协议。而这个核心的内容是就Socket编程。

Socket 是点对点的通讯模式,是全双工的。是靠IP地址进行寻址访问的。

根据设计又几种模式: 点对点 (适合两者之间大文件的传输)  服务器模式(聊天,webapi等)

这里主要讨论: 服务器模式

 Socket 编程需要引用

using System.Net;
using System.Net.Sockets;

 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\r\n";   //状态行
27                     byte[] statusline_to_bytes = Encoding.UTF8.GetBytes(statusline);
28 
29                     string content =
30                     "" +
31                         "" +
32                             "socket webServer  -- Login" +
33                         "" +
34                         "" +
35                            "
" + 36 "欢迎您!" + "" + ",今天是 " + DateTime.Now.ToLongDateString() + 37 "
" + 38 "" + 39 ""; //内容 40 41 42 byte[] content_to_bytes = buffer; 43 44 string header = string.Format("Content-Type:text/html;charset=UTF-8\r\nContent-Length:{0}\r\n", 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)'\r', (byte)'\n' }); //发送空行 51 st.Send(Encoding.UTF8.GetBytes(content)); //发送正文(html) 52 st.Close(); 53 54 } 55 56 } 57 }
View Code

 

转载于:https://www.cnblogs.com/duchyaiai/p/8651541.html

你可能感兴趣的:(模拟.net Core ---- http/tcp 通讯-- 服务器模式)