The communication process and schematic diagram from client to server are very good

Learning anything, as long as we understand its principle, will be similar. Now I want to summarize the communication process from client to server. Only when we understand the principle, can we understand that when the wrong problem occurs in our program development process, we can better solve the problem.

We first need to understand a conceptual Vocabulary: Socket

Socket originally means "hole" or "socket". As a process communication mechanism, take the latter meaning. Also known as "socket", which describes the IP address and port, is a handle to a communication chain. (in fact, it is used for communication between two programs. )Socket is very similar to a telephone socket. Take a telephone network for example. The two sides of a phone call are equivalent to two procedures for communicating with each other. A phone number can be regarded as an IP address. Before any user makes a call, he / she should first possess a telephone, which is equivalent to applying for a socket; at the same time, he / she should know the number (IP address) of the other party, which is equivalent to that the other party has a fixed socket. Then dial the call to the other party, which is equivalent to making a connection request. If the other party is present and free, pick up the phone microphone, the two parties can make a formal call, which is equivalent to a successful connection. The process of communication between the two sides is the process of sending signals from one side of the telephone and receiving signals from the other side. It is equivalent to sending data to and receiving data from the socket. After the end of the call, a party suspending the phone is equivalent to closing the socket, canceling the connection and completing the communication.

The above communication takes two people's communication as an example to explain the communication in general, but now if one of them is a foreigner (speaking English) and the other is a Chinese (speaking Mandarin), if both of them can't understand each other's communication, then their communication can't be completed. But if we give a rule that we can only speak Mandarin to both sides of the conversation, then there will be no obstacle for both sides to communicate. This leads to the communication protocol.

There are two types: (Tcp protocol and Udp protocol):

Tcp protocol and Udp protocol are a kind of data syntax for communication and transmission on two hardware devices.

– flow Socket (STREAM):

TCP is a connection oriented Socket. It is safe but inefficient for connection oriented TCP service applications. TCP: is transmitted in the form of stream.

– DATAGRAM Socket:

It is a connectionless Socket, corresponding to the connectionless UDP service application. It is not secure (lost, disordered order, analysis and rescheduling at the receiving end and request for retransmission), but it has high efficiency. UDP: the packet is divided into several pieces of numbers and then transmitted. In the process of transmission, it is easy to lose data. But the transmission speed is faster than that of TCP.

Socket communication process

  • Demo:
  • Server side:

– apply for a socket (socketWatch) to monitor

- bind to an IP address and a port

– turn on listening and wait for the connection of the receiving client

- create a socket(socketConnection) to communicate with the connected client when there is a connection

– instant monitoring, waiting for the next customer's connection

The code is as follows:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Net.Sockets;

using System.Net;

using System.Threading;

namespace MyChatRoomClient

{

    public partial class FChatClient : Form

    {

        public FChatClient()

        {

            InitializeComponent();

            TextBox.CheckForIllegalCrossThreadCalls = false;

        }

        Thread threadClient = null; //The thread that the client is responsible for receiving data messages from the server

        Socket socketClient = null;//Client socket

//Client sends connection request to server

        private void btnConnect_Click(object sender, EventArgs e)

        {

            IPAddress address = IPAddress.Parse(txtIP.Text.Trim());//Get IP

            IPEndPoint endpoint = new IPEndPoint(address, int.Parse(txtPort.Text.Trim()));//network node

//Create client socket

            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //Send connection requests to the specified IP and port

            socketClient.Connect(endpoint);

            //Client creation thread listens for messages sent by the server

            threadClient = new Thread(RecMsg);

            threadClient.IsBackground = true;

            threadClient.Start();

        }

        /// <summary>

///Listen to messages sent by the server

/// </summary>

        void RecMsg()

        {

            while (true)

            {

                //Define a receive buffer (2M byte array)

                byte[] arrMsgRec = new byte[1024 * 1024 * 2];

                //Store the received data into the arrMsgRec array and return the length of the data actually received

               int length=  socketClient.Receive(arrMsgRec);

                //At this time, all elements of the array are converted into strings, and only a few characters sent by the server are actually received

               string strMsgRec = System.Text.Encoding.UTF8.GetString(arrMsgRec, 0, length);

                ShowMsg(strMsgRec);

            }

        }

        void ShowMsg(string msg)

        {

            txtMsg.AppendText(msg + "\r\n");

        }

    }

}

Communication process diagram

From the above flow chart, we can see that there is a basic communication flow between the client and the server. It summarizes the function of the Socket general application mode (client and server):

Server side: there are at least two sockets. One is that the server is responsible for listening to the connection request sent by the client, but not communicating with the requested client. The other is that whenever the server successfully receives the client, it creates a socket on the server side to communicate with the requested client

Client: Specifies the server-side address and port to connect, and initializes a TCP connection to the server by creating a socket object.

Reprinted from: http://www.codeceo.com/article/client-to-server.html

 

17 original articles published, 36 praised, 30000 visitors+
Private letter follow

Tags: socket network Windows encoding

Posted on Sat, 18 Jan 2020 23:43:09 -0800 by dcuellar