Socket communication synchronous communication

Quote: https://www.cnblogs.com/zpyplan/p/10493311.html

In recent days, I have learned socket communication, socket atmosphere synchronous communication and asynchronous communication. Today, I will talk about synchronous communication, and then I will talk about asynchronous communication. In terms of asynchronous communication, synchronous communication is relatively simple.

SOCKET principle
1, socket concept
socket is the cornerstone of communication and the basic operation unit of network communication supporting TCP/IP protocol. It is an abstract representation of the endpoint in the process of network communication, including five kinds of information necessary for network communication: the protocol used for connection, the IP address of the local host, the protocol port of the local process, the IP address of the remote host, and the protocol port of the remote process.
When the application layer communicates data through the transport layer, TCP will encounter the problem of providing concurrent services for multiple application processes at the same time. Multiple TCP connections or application processes may need to transfer data over the same TCP protocol port. In order to distinguish different application processes and connections, many computer operating systems provide Socket interfaces for the interaction between applications and TCP / IP protocols. The application layer and the transport layer can distinguish the communication from different application processes or network connections through the Socket interface to realize the concurrent service of data transmission.
2, Establish socket connection
To establish a Socket connection, at least one pair of sockets is required, one of which runs on the client, called ClientSocket, and the other runs on the server, called ServerSocket.
The connection process between sockets is divided into three steps: server monitoring, client request and connection confirmation.

  1. Server monitoring: the server socket does not locate the specific client socket, but is in the state of waiting for connection, monitoring the network state in real time, waiting for the connection request of the client
  2. Client request: refers to the connection request made by the socket of the client, and the target to be connected is the socket of the server. For this reason, the socket of the client must first describe the socket of the server it wants to connect to, indicate the address and port number of the socket on the server side, and then make a connection request to the socket on the server side.
  3. Connection confirmation: when the server socket monitor hears or receives the connection request from the client socket, it responds to the request from the client socket, establishes a new thread, and sends the description of the server socket to the client. Once the client confirms the description, the two sides formally establish the connection. The server socket continues to listen and receive connection requests from other client sockets.

3, SOCKET connection and TCP connection
When creating a socket connection, you can specify the transport layer protocol to use. Socket can support different transport layer protocols (TCP or UDP). When using the TCP protocol to connect, the socket connection is a TCP connection.

4, Socket connection and HTTP connection
As the Socket connection is usually a TCP connection, once the Socket connection is established, the two sides of the communication can start sending data content to each other until the two sides are disconnected. However, in the actual network application, the communication between the client and the server often needs to pass through multiple intermediate nodes, such as routers, gateways, firewalls, etc. Most firewalls will close the connection in the inactive state for a long time by default, resulting in the disconnection of Socket connection, so it is necessary to tell the network through polling that the connection is in the active state.
The HTTP connection uses the "request response" method, which not only needs to establish the connection first, but also needs the client to send the request to the server before the server can reply the data.
In many cases, the server needs to actively push data to the client to keep the real-time and synchronous data between the client and the server. At this time, if the two sides establish a Socket connection, the server can directly transmit the data to the client; if the two sides establish an HTTP connection, the server needs to wait until the client sends a request before transmitting the data back to the client. Therefore, the client sends the connection request to the server regularly, not only to keep online, but also to "inquire" the server Whether there is new data, and if so, pass the data to the client.

5, Schematic diagram of communication between Socket server and client

6, Server and client code

(1)Cient:

1: Create a Socket image;

2: Use the Connect() method of socket pair image to send the connection request to the server with the EndPoint pair image established above as the parameter;

3: If the connection is successful, send the information to the server using the Send() method of the socket pair image;

4: The Receive() method of socket pair image is used to receive the information sent by the server;

5: Remember to turn off socket after communication;

Sum up

1. server side

1.new a socket

2.bind

3.listen

4.accept

5.send

6.receive

7.close

That is: confirm the ip and port number, new a socket, bind, listen, accept, send, accept data, close

The code is as follows

using System.Net.Sockets;
using System.Net;
using System.Threading;
using System;
using System.Text;

namespace SocketServer
{
    class Program
    {
        private static byte[] result = new byte[1024];
        private static int myProt = 8885;   //port 
        static Socket serverSocket;
        static void Main(string[] args)
        {
            //Server IP address 
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//new a socket
            serverSocket.Bind(new IPEndPoint(ip, myProt));  //Binding IP address: Port 
            serverSocket.Listen(10);    //Set up to 10 queued connection requests 
            Console.WriteLine("lsnrctl start{0}Success", serverSocket.LocalEndPoint.ToString());
            //Send data through ClientSocket 
            Thread myThread = new Thread(ListenClientConnect);//Open a thread and listen all the time
            myThread.Start();
            Console.ReadLine();
        }

        /// <summary> 
        ///Listen for client connections 
        /// </summary> 
        private static void ListenClientConnect()
        {
            while (true)
            {
                Socket clientSocket = serverSocket.Accept();
                clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
                Thread receiveThread = new Thread(ReceiveMessage);//Open a thread to receive messages
                receiveThread.Start(clientSocket);
            }
        }

        /// <summary> 
        ///Receive message 
        /// </summary> 
        /// <param name="clientSocket"></param> 
        private static void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;
            while (true)
            {
                try
                {
                    //Receiving data through clientSocket 
                    int receiveNumber = myClientSocket.Receive(result);
                   
                    Console.WriteLine("Receive client{0}news{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    myClientSocket.Shutdown(SocketShutdown.Both);
                    myClientSocket.Close();
                    break;
                }
            }
        }
    }
}

Summary client:

1.new socket

2 Connect

3.receive

4.send

That is: new a socket, connect (target ip, port), receive data, send data

The code is as follows

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;


namespace SocketClient
{
    class Program
    {
        private static byte[] result = new byte[1024];
        static void Main(string[] args)
        {
            //Set server IP address 
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                clientSocket.Connect(new IPEndPoint(ip, 8885)); //Configure server IP and port 
                Console.WriteLine("Successfully connected to server");
            }
            catch
            {
                Console.WriteLine("Failed to connect to the server, please press enter to exit!");
                return;
            }
            //Receiving data through clientSocket 
            int receiveLength = clientSocket.Receive(result);
            Console.WriteLine("Receive server message:{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
            //Sending data through clientSocket 
            for (int i = 0; i < 10; i++)
            {
                try
                {
                    Thread.Sleep(1000);    //Wait 1 second 
                    string sendMessage = "client send Message Hellp" + DateTime.Now;
                    clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
                    Console.WriteLine("Send message to server:{0}" + sendMessage);
                }
                catch
                {
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                    break;
                }
            }
            Console.WriteLine("After sending, press enter to exit");
            Console.ReadLine();
        }
    }
}

 

 

Published 17 original articles, praised 0, visited 850
Private letter follow

Tags: socket network encoding ascii

Posted on Thu, 05 Mar 2020 01:32:42 -0800 by explore