"Socket communication" on the principle of socket communication and Python implementation

Source: Internet
Author: User

Socket (socket) communication { network communication is actually the communication between sockets }, first understand the concept: "from Baidu Encyclopedia"

"Two programs use a two-way communication connection to exchange data, and one end of the connection is called a socket. "

It can be said that the socket is a network programming interface (API), it defines a standard, and TCP/IP encapsulation, to achieve the ability of network transmission data.

This article by default you already understand the IP, port and other basic network concepts, if not understood, please visit: https://baike.baidu.com/item/IP/224599

We imagine such a scene, if two people, want to send each other a gift "with a certain Wind express", then everyone needs to know what the other person's information?

    1. Address "IP": Where else would you have sent The courier company? "Or what computer would you have the Internet provider send the data to?" 】
    2. Name "Port": a location does not necessarily live a person ah, express brother how to know who to send? "A computer may not have only one program to use the network Ah, how does the system know which program to pass data to?" 】

A little more, express company has many kinds of, not necessarily have to choose a wind express, you can also use a certain express, a courier, a country post and so on, each has its own characteristics. In the socket communication is also the case, divided into TCP, UDP two kinds.

TCP (Transmission Control Protocol, Transmission protocol ) is a connection -based protocol, which means that a reliable connection must be established with each other before the data is formally sent and received.

UDP (User Data Protocol, Subscriber Datagram Protocol ) is the protocol that corresponds to TCP. It is a non-connected protocol that does not establish a connection with the other, but sends the packet over directly !

Keywords I have been marked out, with the above scenario introduction, can be easily understood. Since each has its own characteristics, then according to the biological theorem: "Structure-determining function", we are also very easy to know that these two things must have a different place.

TCP, because it is transmitted based on both sides of the connection, so its connection and data transmission is very stable and reliable , you can make a computer sent a stream of bytes intact to another computer. This type of communication is chosen for applications that require very high reliability.

UDP, it is certainly not very stable, it is suitable for only a small amount of data at a time, the reliability of the application environment is not high. In fact, we often use the "ping" command to send ICMP packets to the other host "self-Baidu", and then the other host to confirm the receipt of the packet, if the packet arrives timely feedback back, then the network is through. By the way, the chat function of QQ mostly uses the UDP to realize, because this can make the transmission rate extremely fast, but at the same time will also appear the failure situation, more extreme is encounters the change situation.

In addition, there are two pairs of concepts to understand about socket communication: The concept of long connection and short connection , asynchronous and synchronous "is difficult to understand, but you can not understand, will not hinder your implementation of small projects, after you achieve a few small projects, and then turn to look at this piece, You're going to have a sense of epiphany.

1. Long connection
As the name implies, a long connection is a connection that takes longer to connect: connect-and-transmit data------............-->
The socket is connected regardless of whether it is used, but is less secure, although it occupies a smaller resource.

2. Short connection
As the name implies, a short connection is a shorter connection, but it can be connected multiple times: connect-to-transmit data--end connection--transfer data ............--> end
After the socket connection is sent, the connection is disconnected immediately after receiving the data.

1. Asynchronous
Message sending and receiving are separate, independent and mutually exclusive . This approach is divided into two different situations:
(1) Asynchronous duplex: Receive and send in the same program, by two different sub-processes are responsible for sending and receiving respectively
(2) Asynchronous Simplex: Receive and send is done with two different programs.

2. Synchronization
The message is sent and received synchronously , which waits to receive the return message after the message is sent. Synchronous mode generally need to consider the time-out problem, that is, the message can not wait indefinitely after sending out, need to set the timeout period, more than the time the sender no longer wait for the read return message, the direct notification timeout return.
In a long connection, it is generally not possible to determine when the read-write ends, so it is necessary to add a length message header. The reading function reads the length of the message header, and then reads the corresponding length of the message according to the length.

Forgive me, synchronous async really did not find the right picture, I really can't think how to lift the chestnut can let the reader understand better. My personal experience is: To do a test machine "test machine and the Web server with the socket to transmit data" only after understanding.

Below we need to understand how these courier companies to achieve interactive?

First look at this diagram, in fact, this map can be summed up everything, but in order to make most of the better understanding, I explained again.

First, the client and the server will create a separate socket, the server socket needs to bind () to the upper port, start listen () for real-time monitoring, and wait for the client access, that is, accept (). While the client needs to establish the connect () connection through the server IP and port two parameters, at this point, the server will get the information of the new client connection, start read () Wait for the client data descendants, the client if successfully received the service side of the successful connection, continue to execute write () To the service side of the data, in the same way, the server also use such a mode to repay the client's data, know that the client shuts down, the service side will receive the client exits the connection message, the servers re-enter the waiting state, waiting for the new client to enter.

The following is an example written in Python, and other languages are implemented in the <WINSOCKET2> library by following the standard above and the extension libraries that C + + uses.

1 ImportSocket2 #Service Side3New_socket = Socket.socket ()#creating a Socket object4IP ="127.0.0.1"          #get Local Host name5Port = 52052#Setting up Ports6New_socket.bind ((IP, port))#Binding Port7New_socket.listen (5)#wait for the client to connect and set the maximum number of connections8  whileTrue:9New_cil, addr = New_socket.accept ()#establish a client connection. Ten     Print('address of the new incoming client:', addr) One     Print(New_cil.recv (). Decode ()) ANew_cil.send ('the answer is 6 .') -New_cil.close ()#Close Connection
ImportSocket#ClientIP ="127.0.0.1"Port= 52052New_socket= Socket.socket ()#creating a Socket objectNew_socket.connect ((Ip,port))#ConnectionNew_socket.send ("ask me to calculate how much 1+5=? ". Encode (encoding='Utf-8'))#Occurrence DataPrint("client to the server: Ask me to calculate how much 1+5=? ") Back_str= New_socket.recv (). Decode ()#End DataPrint("The server is sent to the client:"+back_str) new_socket.close ()#shutting down the clientPrint("Client End Run")

Life is short, I use python! Next Door C language implements this at least 200 lines of code!

"Socket communication" on the principle of socket communication and Python implementation

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.