Dealing with the application layer: TCP socket programming

TCP

Transmission Control Protocol (TCP) is a connection-oriented, reliable, and byte-based transport layer communication protocol, defined by IETF RFC 793. TCP is designed to adapt to the hierarchical protocol hierarchy supporting multiple network applications. The pair of processes in the host computers connected to different but interconnected computer communication networks rely on TCP to provide reliable communication services. TCP assumes that it can obtain simple, possibly unreliable datagram services from lower-level protocols. In principle, TCP should be able to operate on various communication systems from hard-wired to packet-switched or circuit-switched networks. - Baidu Encyclopedia


The TCP protocol provides users with two services, namely connection-oriented services and reliable data transmission services, we briefly introduce. To put it simply, connection-oriented means that a connection needs to be established between the client and the server. Before the data at the application layer starts to interact, the TCP protocol first requires the client and server to perform a handshake . Doing this is equivalent to telling each other that the next data interaction is required. Please prepare for both parties. The specific implementation is for the two parties to exchange information at the transport layer. After the handshake phase is over, a TCP connection can be established. After the data exchange between the two applications is completed, the connection needs to be cut off.
Next, let's look at what is a reliable data transmission service , that is, the data exchange between the two parties is guaranteed by the TCP protocol, and the data sent by each other can be transmitted to the other party in the correct order without difference . That is, TCP will send the byte stream from the sender through the socket, and deliver the byte stream to the receiver's socket while ensuring that the bytes are not lost and redundant.
In addition, TCP also provides some good mechanisms, we give two examples. The congestion control mechanism will detect whether the network status of the two parties is good, and if the network is congested, it will send data from one party. The flow control mechanism will ensure that the sending speed will not exceed the receiver's ability to receive data. It is worth mentioning that TCP does not provide delay guarantee and minimum bandwidth guarantee.

Socket programming (TCP)

Because TCP is a connection-oriented protocol, we cannot simply throw work to the socket. According to the introduction above, we need to first shake hands between the client and server to establish a TCP connection. To create this connection, we need to associate the IP addresses and port numbers of the client and client to the connection to achieve the purpose of associating the sockets of both parties.
What requirements does this place on the server and the client? For the server, in order to be able to reach the client during the handshake phase, the server process needs to be ready to accept such information that the server process must start running first, and in order to be able to recognize the handshake data information, the server socket With such a function, we call such a socket a welcome socket . And the client? The client needs to have the ability to initiate a handshake request.

Next, let's talk about the establishment of a TCP connection. Since the handshake is initiated by the client, the client establishes a TCP socket. This socket needs to specify that the server has the IP address and port number of the server's welcome socket , then the client will initiate a three-way handshake at the transport layer , and the TCP connection will be established after the three-way handshake ends.
During the three-way handshake, if the welcome socket receives the handshake message, it will generate a new one. This new socket is used to specifically connect the client socket, which is called the connection socket. Pick up . With a connection socket, the client and server interact as if they were connected to a pipe.

greet! (Program requirements)

Let's make a basic thing, let the client and server greet each other!

  1. The prompt message is displayed, and the customer enters his name from the keyboard;
  2. Send the data to the server through the program;
  3. The server receives the data and generates a greeting message, such as "Hello!";
  4. The server sends the data back to the client;
  5. The customer receives the data and displays the returned data.
  • The following is implemented in Python.

TCPClient

We go step by step, "A clever woman can't cook without rice ". First of all, I need some tools to make sockets, so we don't need to make wheels. There is a module in Python dedicated to this task, called " socket " We will include it first.

from socket import *

Next, I need to explain the destination host of the received packet, and then create 2 variables to store it.

Name = '名字'    #用字符串来存目的地址,“名字”需要替换为目的地的 IP 地址或域名 
Port = 端口号    #“端口号”需要替换为一个存在的端口,例如 12000,注意不要“串线”

Well, next we need to generate a socket to work, let's just look at the code. But now we may be confused by this code, what is this? Don't worry, we will know "AF_INET" and "SOCK_STREAM" when we learn the network layer. Simply put, this code creates a TCP type socket, we just write it down first.

Socket = socket(AF_INET,SOCK_STREAM)

Next we will ask the customer to enter his name as the request says. The interactivity of the software is better, we can also come to prompt information.

print("现在向服务器打个招呼吧!")
sentence = input("Nice to meet you! My name is ")

When the client sends data to the server, a TCP connection must be established between the client and the server, so we use the " .connect () " method to initiate a connection to the server. The parameters of this method are the server's end address and the corresponding Port. After executing this code, the TCP connection is connected after three handshake.

Socket.connect((Name,Port))

The difference with UDP is that the data we want to transmit does not need to be packaged with the IP address of the server, because we have gone through three handshake and can directly use the established connection to transmit data. The " .send () " method can submit data to the TCP connection and send it to the server.

Socket.send(sentence.encode())

Now that our operation of sending data is over, we need to accept the data next. Waiting for the server to send the data back, we use the " .recv () " method to help us accept it, and then we print it out.

sentence = Socket.recv(1024)
print(sentence.decode())

Remember when we read the file, what do we do after the operation? That is to close the file, which is a good habit. The same is true for sockets, we also need to develop good habits, close a process after it is used up. The ".close ()" method can achieve this function. At this point, the programming is over!

Socket.close()

TCPServer

We just wrote a client-side Python program, now let's write a server-side program. Step by step, first of all, let's first include the " Socket " module.

from socket import *

Next, we need to specify the port number, which means that the socket of my server only accepts the information from a certain port, reflecting a " door to door "! We use a variable to store the port number, and then we have to create a socket as above, we bind the port number to this socket through the ".bind ()" method. Note that this time the welcome socket is made .

Port = 端口号    #“端口号”需要替换为一个存在的端口,例如 12000,注意不要“串线”
serverSocket = socket(AF_INET,SOCK_STREAM)
Socket.bind(('',Port))

After we have created the welcome socket, we are ready to receive the handshake request. You can use the " .listen () " method to accept such requests. The parameters of the method define the maximum number of connection requests (at least 1).

Socket.listen(1)

In order to indicate that the above operation was successfully implemented, we output a prompt message.

print("准备就绪,可以接收分组!")

As a server, we must not only receive the packet once, but we must be constantly preparing the corresponding packets. That is to say, my server must continue to be in working condition. We use an endless loop " while true " to realize that this time the endless loop will not consume too much resources, because after the next statement reads the group, it will take action.
When the client begins to send a handshake request, the welcome socket can use " .accept () " to accept the request, and at the same time generate a " connection socket " for the client to use alone, after the handshake is completed, it can be established by The TCP connection has exchanged information.

while True:
    connectionSocket,addr = Socket.accept()
    sentence = connectionSocket.recv(1024).decode()
    backSentence = "Hello, " + sentence.upper() + "! My name is Han Meimei."
    connectionSocket.send(backSentence.encode())
    connectionSocket.close()

After completing the information interaction with the client, the connection socket must be closed, but the server can remain open to receive the next handshake request. Some friends will ask, when will this endless cycle stop? It's so simple, just close the program when you don't want to use it!

Program test

Since I have no friends to accompany me, I had to do a test on one machine. As mentioned earlier, we need to ensure that the server program remains running before sending bytes. What if the server is not running?

" Positive refusal! " From this we can see that it would not work without running the server program. So we start the server program "TCPServer.py" first.

Seeing the prompt message proves that the server started very successfully, then start the client program.

This time it's finally okay, let's say hello!

The program fulfilled our needs!

References

"Computer Network" edited by Xie Xiren, Electronic Industry Press
"Computer Network Top-Down Method" [US] by James F. Kurose, Keith W. Ross, translated by Chen Ming, Mechanical Industry Press
on TCP three-way handshake, this is me I have seen the best interpretation. The easy-to-understand
TCP three-way handshake and four waved comprehension and interview questions (very comprehensive). The
TCP three-way handshake explains in detail
why TCP is a three-way handshake, not two or four times?

Guess you like

Origin www.cnblogs.com/linfangnan/p/12736715.html