Home  >  Article  >  Backend Development  >  C# uses Socket to create a small Web Server code sharing

C# uses Socket to create a small Web Server code sharing

黄舟
黄舟Original
2017-03-21 11:40:111870browse

This article mainly introduces the relevant information about C# using Socket to create a small Web Server. The article introduces it in detail through sample code. Friends in need can refer to it. Let’s take a look. Bar.

To implement the Web Server, you can obtain the accessed data through the following code browser access.

Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketWatch.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 81));
socketWatch.Listen(20); // 参数表示最多可容纳的等待接受的传入连接数,不包含已经建立连接的。

Thread thread = new Thread(delegate(object obj)
{
 Socket socketListen = (Socket)obj;
 while (true)
 {
  Socket socket = socketListen.Accept();
  byte[] data = new byte[1024 * 1024 * 4]; // 浏览器发来的数据,限定为 4K。
  int length = socket.Receive(data, 0, data.Length, SocketFlags.None);
  socket.Send(Encoding.UTF8.GetBytes("欢迎访问 www.cftea.com\r\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")));
  socket.Shutdown(SocketShutdown.Both);
  socket.Close();
 }
});

thread.IsBackground = true;
thread.Start(socketWatch);

But the above is just a principle, it will be very complicated in practice. However, even if we want to make a simple Web Server, we still need to solve two problems:

1. Output HTTP header

byte[] body = Encoding.UTF8.GetBytes("欢迎访问 www.cftea.com\r\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
byte[] head = Encoding.UTF8.GetBytes(@"HTTP/1.1 200 OK
Content-Length: " + body.Length + @"
Content-Type: text/plain
Date: " + string.Format("{0:R}", DateTime.Now) + @"
Server: Cftea Web Server

");
socket.Send(head);
socket.Send(body);

As long as it has a specific format, it will be treated as an HTTP header by the browser. The format of the HTTP header is:

  • First line: HTTP/1.x + space + status code + space + description

  • Middle line : Name + colon + space (can also be omitted) + value

  • Last line: Blank line

The format must be correct, Otherwise, it will affect the browser's recognition of HTTP headers and HTTP bodies.

2. Request HTTP header

So far, we don’t know what the URL entered in the browser is. The HTTP header of the request also has a specific format. We only need to get it out and disassemble it to get the URL.

Disassembly is not difficult, let’s talk about how to obtain it. Aren’t the previous data and length always useless? As follows:

string requestText = Encoding.UTF8.GetString(data, 0, length);

Complete code

Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketWatch.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 81));
socketWatch.Listen(20); // 参数表示最多可容纳的等待接受的传入连接数,不包含已经建立连接的。

Thread thread = new Thread(delegate(object obj)
{
 Socket socketListen = (Socket)obj;
 while (true)
 {
  using (Socket socket = socketListen.Accept())
  {
   byte[] data = new byte[1024 * 1024 * 4]; // 浏览器发来的数据
   int length = socket.Receive(data, 0, data.Length, SocketFlags.None);
   if (length > 0)
   {
    string requestText = Encoding.UTF8.GetString(data, 0, length);

    byte[] body = Encoding.UTF8.GetBytes(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
    byte[] head = Encoding.UTF8.GetBytes(@"HTTP/1.1 200 OK
Content-Length: " + body.Length + @"
Content-Type: text/plain
Date: " + string.Format("{0:R}", DateTime.Now) + @"
Server: Cftea Web Server

");
    socket.Send(head);
    socket.Send(body);
   }

   socket.Shutdown(SocketShutdown.Both);
   socket.Close();
  }
 }
});

thread.IsBackground = true;
thread.Start(socketWatch);

Summary

The above is the detailed content of C# uses Socket to create a small Web Server code sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn