The communication process and principle between the client and the server, and the client server

Source: Internet
Author: User
Tags key string

The communication process and principle between the client and the server, and the client server

To learn anything, we only need to figure out its principles, and it will be accessible. Now, I want to summarize the communication process from the client to the server. Only by understanding the principles can we understand that when errors occur during program development, we can better solve the problem.

First, we need to understand a conceptual vocabulary:Socket

The original meaning of socket is "hole" or "socket ". As a process communication mechanism, take the latter meaning. It is also called "socket". It is used to describe the IP address and port and is a communication chain handle. (It is actually used for communication between two programs..) A socket is very similar to a telephone socket. Take a telephone network as an example. The two sides of a phone call are equivalent to two programs for mutual communication. The phone number can be considered as an IP address. Before a call, a user must possess a telephone, which is equivalent to applying for a socket. At the same time, the user must know the number (IP address) of the other party, which is equivalent to a fixed socket. Then, a dial-up call is sent to the other party, which is equivalent to a connection request. If the other party is present and idle, pick up the phone microphone and the two parties can make a formal call, which is equivalent to a successful connection. The communication process between the two parties is the process of sending a signal to the phone and receiving a signal from the phone. It is equivalent to sending data to and receiving data from the socket. After the call is over, one party suspends the phone, which is equivalent to shutting down the socket, canceling the connection, and the communication is complete.

The above communication uses two people as an example to illustrate communication, but now if one person in the communication is a foreigner (speaking english) and one person in the communication is a Chinese (speaking mandarin ), if both of them communicate with each other, they cannot understand what the other party is talking about, so their communication cannot be completed. However, if we give a rule that only Mandarin can be spoken for both parties, there will be no barriers to communication between the two parties. This leads to the communication protocol.

There are two types: (Tcp and Udp ):

The Tcp and Udp protocols are inOn the hardware deviceA Data syntax for communication and transmission.

-STREAM Socket (STREAM ):

It is a connection-oriented Socket. It is secure but inefficient for connection-oriented TCP Service applications. Tcp is transmitted in the form of a stream.

-DATAGRAM Socket (datasync ):

Is a connectionless Socket that corresponds to a connectionless UDP Service Application. unsafe (loss, disordered order, analysis of rescheduling at the receiving end and re-sending required), but high efficiency. udp: Split the data packet into several numbers and then transmit them. Data is prone to loss during transmission. However, the transmission speed is faster than that of TCP.

SocketCommunication Process

  • Demo:

  • Server:

-Apply for oneSocket(SocketWatch) used for listening

-Bind to an IP address and a port

-Enable listening and wait for the connection from the authorized client

-When a connection exists, a client is created to communicate with the connected client.Socket(SocketConnection)

-Resume listening, 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; // IPAdress, IPEndPoint (ip and port) class using System. net. sockets; using System. threading; using System. IO; namespace MyChatRoomServer {public partial class FChatServer: Form {public FChatServer () {InitializeComponent (); TextBox. checkforillegalcrossthreadcils = false; // disable the cross-Thread operation check on the text box} Thread threadWatch = null; // the Thread that listens to client connection requests Socket socketWatch = null; // listener socket private void btnBeginListen_Click (object sender, EventArgs e) {// create a socket for the server to listen to, parameters (using IP4 Addressing protocol, using stream connection, use TCP to transmit data) socketWatch = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); // obtain the IP address object IPAddress address = I in the text box. PAddress. parse (txtIP. text. trim (); // create a network Node object IPEndPoint endpoint = new IPEndPoint (address, int. parse (txtPort. text. trim (); // bind the socket responsible for listening to a unique IP address and port on socketWatch. bind (endpoint); // set the length of the listening queue socketWatch. listen (10); // create the Thread responsible for listening, and input the listening method threadWatch = new Thread (WatchConnecting); threadWatch. isBackground = true; // set it to the background thread threadWatch. start (); // enable the thread ShowMsg ("the server has started the listener successfully ~ "); // IPEndPoint // socketWatch. bind (} // stores all Socket Dictionary <string, Socket> dict = new Dictionary <string, Socket> () for communication between the server and the client (); // saves all the communication sockets on the server. the Receive method Thread Dictionary <string, Thread> dictThread = new Dictionary <string, Thread> (); // Socket sokConnection = null; /// <summary> /// Method for listening to client requests /// </summary> void WatchConnecting () {while (true) // continuously listen to connection requests from new clients {// start to listen to client connection requests. Note: Accep T method, it will block the current thread! Socket sokConnection = socketWatch. accept (); // once a request is received from the client, a socket sokConnection // sokConnection that is responsible for communicating with the client is returned. receive // Add a Client ip port string to the list control, which is the unique identifier of the client lbOnline. items. add (sokConnection. remoteEndPoint. toString (); // Add the socket object sokConnection that communicates with the client to the key-value pair set, and use the Client IP port as the key dict. add (sokConnection. remoteEndPoint. toString (), sokConnection); // create a communication thread ParameterizedThreadStart pts = new ParameterizedThread Start (RecMsg); Thread thr = new Thread (pts); thr. isBackground = true; // set it to thr. start (sokConnection); // Start the thread and input the sokConnection dictThread parameter for the method RecMsg to be called by the thread. add (sokConnection. remoteEndPoint. toString (), thr); // Save the thread in the dictionary, so that you can use ShowMsg ("client connection successful! "+ SokConnection. remoteEndPoint. toString (); // sokConnection. the RemoteEndPoint stores the Ip address and port of the currently connected client. }}/// <summary> // method for the server to listen to the data sent by the client. /// </summary> void RecMsg (object socketClientPara) {Socket socketClient = socketClientPara as Socket; while (true) {// defines a cache for receiving (2 MB array) byte [] arrMsgRec = new byte [1024*1024*2]; // Save the received data to the arrMsgRec array, and returns the length of the actually received data int length =-1; try {leng Th = socketClient. receive (arrMsgRec);} catch (SocketException ex) {ShowMsg ("exception:" + ex. message); // Delete the communication socket object dict from the communication socket set. remove (socketClient. remoteEndPoint. toString (); // deletes the client-connected communication thread object dictThread from the communication thread combination. remove (socketClient. remoteEndPoint. toString (); // remove the interrupted connection ip address from the list: Port lbOnline. items. remove (socketClient. remoteEndPoint. toString (); break;} catch (Exception ex) {ShowMsg ("Exception:" + ex. message); break;} if (arrMsgRec [0] = 0) // determine that the first element of the sent data is 0, it indicates that the text data is sent {// all elements of the array are converted into strings, and only a few characters from the server are actually received: string strMsgRec = System. text. encoding. UTF8.GetString (arrMsgRec, 1, length-1); ShowMsg (strMsgRec);} else if (arrMsgRec [0] = 1) // if it is 1, it indicates that the file data (image/Video/file...) is sent ....) {SaveFileDialog sfd = new SaveFileDialog (); // Save the object if (sfd. showDialog () = System. windows. for Ms. dialogResult. OK) // {string fileSavePath = sfd after the file path is selected. fileName; // obtain the file path to be saved // create a file stream, and then let the file stream create a file using (FileStream fs = new FileStream (fileSavePath, FileMode. create) {fs. write (arrMsgRec, 1, length-1); ShowMsg ("file saved successfully:" + fileSavePath );}}}}} // send the message to the Client private void btnSend_Click (object sender, EventArgs e) {if (string. isNullOrEmpty (lbOnline. text) {MessageBox. show ("select the friend you want to send ") ;} Else {string strMsg = txtMsgSend. text. trim (); // convert the string to be sent to the byte array byte [] arrMsg = System. text. encoding. UTF8.GetBytes (strMsg); // obtain the selected KEY string strClientKey = lbOnline in the list. text; // use the key to find the send method of the socket that communicates with a client in the dictionary set, and send data to the other party try {dict [strClientKey]. send (arrMsg); // sokConnection. send (arrMsg); ShowMsg ("sent data:" + strMsg);} catch (SocketException ex) {ShowMsg ("sending exception:" + ex. message );} Catch (Exception ex) {ShowMsg ("Exception during sending:" + ex. message) ;}}// private void btnSendToAll_Click (object sender, EventArgs e) {string strMsg = txtMsgSend. text. trim (); // convert the string to be sent to the byte array byte [] arrMsg = System. text. encoding. UTF8.GetBytes (strMsg); foreach (Socket s in dict. values) {s. send (arrMsg);} ShowMsg ("group completion! :)");} # Region Display message // <summary> // Display message // </summary> /// <param name = "msg"> </param> void ShowMsg (string msg) {

  

  • Client:

-Apply for a socket (socketClient)

-Connect to the server (specifying the IP address and port number)

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. checkforillegalcrossthreadcils = false;} Thread threadClient = null; // The Thread where the client is responsible for receiving data messages from the server Socket socketClient = null; // client socket // the client sends a connection request to the server private void btnConnect_Click (object sender, EventArgs e) {IPAddress address = IPAddress. parse (txtIP. text. trim (); // obtain IP IPEndPoint endpoint = new IPEndPoint (address, int. parse (txtPort. text. trim (); // network node // create a client Socket socketClient = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); // send a connection request socketClient to the specified IP address and port. connect (endpoint); // The client creation Thread listens to the Message threadClient = new Thread (RecMsg) from the server; threadClient. isBackground = true; threadClient. start () ;}/// <summary> /// listen to messages sent from the server // </summary> void RecMsg () {while (true) {// define a cache for receiving (2 MB byte array) byte [] arrMsgRec = new byte [1024*1024*2]; // Save the received data to the arrMsgRec array and return the length of the received data. int length = socketClient. receive (arrMsgRec); // converts all elements of the array into strings, and only a few characters from 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

The above flowchart shows a basic communication process between the client and the server.The role of the general application mode (client and server:

Server:There are at least two sockets. One is that the server is responsible for listening to the client for sending connection requests, but is not responsible for communicating with the requested client. The other is that when the server successfully receives the client, however, a socket is created on the server to communicate with the requested client.

Client:Specify the server address and port to be connected, and create a socket object to initialize a TCP connection to the server.

 

 

 

This blog Source: http://www.codeceo.com/article/client-to-server.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.