You can also write a server - C # Socket learn 2

Continued article "You can also write a chat program - C # Socket learn 1"

Foreword

Here that the server is a Web server, it is similar to IIS, Tomcat and the like, to respond to service requests browser.

Socket simulation browser Url Get request

The first browser request is HTTP protocol. We have said on one, HTTP connection is short, it runs off, is stateless. So we do not need another open thread loop waiting while waiting for a response.
That is, we just need to build through the Socket and server connections, then send the request, and then receives the response from the server, thus completing a request.
However, we generally visit pages at all times through the domain name, there is no IP port, how to establish a connection and the server. Here it is necessary to use several articles on class we introduced the:

//根据DNS获取域名绑定的IP
foreach (var address in Dns.GetHostEntry("www.baidu.com").AddressList)
{
    Console.WriteLine($"百度IP:{address}");
}

//字符串转IP地址
IPAddress ipAddress = IPAddress.Parse("192.168.1.101");

//通过IP和端口构造IPEndPoint对象,用于远程连接
//通过IP可以确定一台电脑,通过端口可以确定电脑上的一个程序
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 80);

For all default HTTP port 80 is not shown (for simplicity here is not considered a HTTPS)
know the IP and port, the connection can be established, in order to get the correct response, what we should send a message to the server? Here it is necessary to use the HTTP protocol.
Specific agreements can not say here, let's take a look at F12 request message browser, then Yihuhuhuapiao try to http://fanyi-pro.baidu.com example. (Now to find non-HTTPS address is not easy)

and then we implement the code as follows:

void ...()
{
    //得到主机信息
    IPHostEntry ipInfo = Dns.GetHostEntry(new Uri("http://fanyi-pro.baidu.com").Host);
    //取得IPAddress[]
    IPAddress[] ipAddr = ipInfo.AddressList;
    //得到服务器ip
    IPAddress ip = ipAddr[0];
    //组合远程终结点
    IPEndPoint ipEndPoint = new IPEndPoint(ip, 80);
    //创建Socket 实例
    Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    
    //尝试连接
    socketClient.Connect(ipEndPoint);
    //发送请求
    Send(socketClient);
    //接收服务器的响应 
    Receive(socketClient); 
}

//接收来自服务端的消息
void Receive(Socket socketClient)
{
    byte[] data = new byte[1024 * 1024];
    while (true)
    {
        //读取客户端发送过来的数据
        int readLeng = socketClient.Receive(data, 0, data.Length, SocketFlags.None);
        textBox2.AppendText($"{socketClient.RemoteEndPoint}:{Encoding.UTF8.GetString(data, 0, readLeng)}\r\n");
    }
}

//发送消息到服务端
void Send(Socket socketClient)
{
    //为了方便演示,仅用请求报文的前两行即可。(切记:需要严格按照报文格式。如,最后需要连续两次换行)
    var msg = $"GET / HTTP/1.1\r\nHost: {new Uri(textBox1.Text).Host}\r\n\r\n";
    socketClient.Send(Encoding.UTF8.GetBytes(msg));
}

The whole process is:

  • 1, dns service to domain names into ip
  • 2, by ip and port and server to establish a connection (three-way handshake)
  • 3, get html document
  • 4, which according to the document link (js, css, img) then repeat the process

[Note]: When sending messages need strict accordance with the packet format. For example, the last two requiring continuous wrap, end of the line with no spaces and so on.

Renderings:

Implement Web server with Socket

Implement Web server and Socket chat service on one end we are in fact similar.
Difference is that the resolution request message, and then press the standard HTTP protocol reply message in response (I here for simplicity, there is no standard protocol play, just to achieve the effect of the surface)
code is as follows:

void ...()
{
    //1 创建Socket对象
    Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    //2 绑定ip和端口
    IPAddress ip = IPAddress.Parse("127.0.0.1");
    IPEndPoint ipEndPoint = new IPEndPoint(ip, 80);
    socketServer.Bind(ipEndPoint);

    //3、开启侦听(等待客户机发出的连接),并设置最大客户端连接数为10
    socketServer.Listen(10); 
    
    //阻塞等待客户端连接
    Task.Run(() => { Accept(socketServer); });
}

//4 阻塞等待客户端连接
private static void Accept(Socket socketServer)
{
    while (true)
    {
        //阻塞等待客户端连接
        Socket newSocket = socketServer.Accept();
        Task.Run(() => { Receive(newSocket); });
    }
}

//5 读取客户端发送过来的报文
private static void Receive(Socket newSocket)
{
    byte[] data = new byte[1024 * 1024];
    while (newSocket.Connected)
    {
        //读取客户端发送过来的数据
        int readLeng = newSocket.Receive(data, 0, data.Length, SocketFlags.None);
        //读取客户端发来的请求报文
        var requst = Encoding.UTF8.GetString(data, 0, readLeng);
        
        //解析请求报文的请求路径(可以解析请求路径、请求文件、文件类型)
        var requstFile = requst.Split("\r\n")[0].Split(" ")[1];
        //回复客户端响应报文
        Send(newSocket, requstFile);
    }
}

//6 回复客户端响应报文
private static void Send(Socket newSocket, string requstFile)
{
    //这里如果请求的根目录,默认显示Index.html
    if (requstFile == "/" ) requstFile = "/Index.html";

    var msg = File.ReadAllText(Directory.GetCurrentDirectory() + requstFile);
    //把消息内容转成字节数组后发送
    newSocket.Send(Encoding.UTF8.GetBytes(msg));
   
    //回复响应后马上关闭连接
    newSocket.Shutdown(SocketShutdown.Both);
    newSocket.Close();
}

Results are as follows:


From this we can know why the .net core without the need of iis, a black window provides access to the URL. In fact, that is KestrelServer by Socket binding and port monitoring service provided.
[Note]: We are bound to ip 127.0.0.1 socketServer.Bind(ipEndPoint), so when we tested only enter localhost or 127.0.0.1 in your browser. If you want to access by internal and external ip, we can bind any ip IPAddress.Any. As socketServer.Bind(new IPEndPoint(IPAddress.Any, port)).

Why not see three-way handshake

For HTTP / TCP how much we may have heard of three-way handshake, but we did not see things in the preparation of relevant Web server using Socket ah, this is how it was.
Because we executed on the client connection socketClient.Connect(ipEndPoint)time has been a three-way handshake

concrete can peruse a small tank Gangster article.
That we are in Socket, TCP, HttpClient time in C # simply do not pay attention to these details.
Further socket has three different types: stream sockets, datagram sockets and raw sockets. Two are standard sockets, corresponding to TCP and UDP. The underlying raw socket is more Niubi more, the average developer is generally out of reach.
We're talking HTTP, TCP, UDP and the like are network protocol, that protocol in the end what is? In layman's really just you and me a contract between him and that everyone accordance with the provisions of the agreement can be said to it.
The HTTP is built on top of TCP, which is after the agreed basis of the agreement plus they can become a new agreement. Socket next chapter we will use to achieve agreement on ModbusTCP register read and write.

End

Guess you like

Origin www.cnblogs.com/zhaopei/p/Socket2.html