【Computer Network】TCP&UDP Communication Experiment

Since the TCP/UDP communication protocol is so important, how should we simply simulate it? The following is a simple simulation of TCP and UDP communication using the method of socket packets in Python. The experimental content comes from "Computer Networks - Top-Down Method Seventh Edition".

UDP communication experiment

Experimental goal: use Python's socket package to realize UDP communication

Realize the effect:

client:

Service-Terminal:

UDP communication principle

If we want to implement UDP communication experiment with socket package, then we need to know the function of socket first. A socket, also known as a socket, is used to send packets from an application to an underlying structure. The following is the relationship between the socket and the application layer and the transport layer. The socket is like the house, the application is the house, and our message is the goods transported from the house to the outside (transport layer).

After understanding the role of socket, we need to see how to use Python to design a UDP communication program. According to the principle of communication, an effective communication application system should include information sending procedures and information receiving procedures. So we should also design a client program and server program.

client

Before designing the client program, we first need to import the socket toolkit.

import socket

When we import the toolkit, we need to determine where the message sent by our client should be sent, that is to say, we need to determine the IP of the server, but this is not enough. After we send the message to the host, we need to determine Which process on the host we send the message to receive, that is to say which host number needs to be sent to. For this reason, we define two variables to store the server IP and port number respectively, and the operating system can help us specify which port our client sends from.

serverIP = '192.168.xx.xx'
severPort = 10000

The server port number I chose here is 10000, but before we conduct communication experiments, we first need to ensure that the port we use is not occupied by other processes. If you want to check whether the port is occupied, you can enter the netstat -ano command to check the status of all ports. If you want to find out a certain port, you can directly enter netstat -ano|findstr "port number" to determine whether the port is occupied.

The next step is to create a socket UdpClientSocket . The socket function in the socket package is used to create a socket. The object it returns is the socket we need. Here we need to pass two parameters socket.AF_INET and socket .SOCK_DGRAM , which are used to determine the use of IPV4 and UDP protocols respectively. Here we need to send the client's data to the server, so I design a message variable to receive user input.

UdpClientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print('**********客户端************')
message = input('请输入要发送的句子:')

Then we need to send the user input message we got, specifically call the sendto function in the created socket variable , and pass our data, but we need to pay attention that we need to convert the data from string to word Pass it out after the festival, so you need to call the encode() function, and finally pass a tuple. The first element of this tuple is the server IP, and the second parameter is the port number called by the server.

UdpClientSocket.sendto(message.encode(), (serverIP, severPort))

Then we need to design a feedback to the client to prove that the server has received the data. To do this, we call the recvfrom function in the socket object, which will return a tuple. The first element of this tuple is the information returned by the server. The second is the socket address (IP and port number) of the server, and its parameter 2048 means to fetch data with a cache length of 2048. Finally, we output the data returned by the server from bytes to strings again on the client side, and also output the IP and port number of the server. Finally, close the socket again.

modifiedMessage, serverAddress = UdpClientSocket.recvfrom(2048)
print(modifiedMessage.decode())
print('服务器的IP地址为:',serverAddress[0], '服务器端口号为:', serverAddress[1])
UdpClientSocket.close()

Service-Terminal

After designing the client, the next step is to design the settings of the server. First, import all the functions in the data package socket as usual, and then point out the server port number and create the socket as usual.

from socket import *
serverPort = 10000
serverSocket = socket(AF_INET, SOCK_DGRAM)

 Next, you need to use the following code to bind the 10000 port number of the server to the server. The binding method is to bind the local IP and the port number. The local IP can be omitted (replaced by ' '), but the port number needs to be written. Come out, so that the data sent by the client can be sent to the server through this socket.

serverSocket.bind(('', serverPort))

Finally, an infinite loop is designed. This infinite loop has been pending, waiting for us to send information. Once the information is received, the processing we design here is to convert the information into bytes and send a feedback message to the client.

while 1:
    message, clientAddress = serverSocket.recvfrom(2048)
    modifiedMessage = '您发的'+message.decode()+'已经接收到了'
    serverSocket.sendto(modifiedMessage.encode(), clientAddress)

TCP communication experiment

TCP communication principle

TCP communication is different from UDP communication. TCP communication is more secure and guaranteed. Naturally, its implementation method is very different from before. Before the TCP communication, a TCP connection needs to be established between the client and the server, and the message is communicated between the two parties through this connection. Unlike before, the message communication does not need to attach the destination IP and port number. , it only needs to communicate through an open TCP connection channel.

Before communication, the client will open a socket for external communication. The difference from the UDP experiment is that the server will open two sockets during TCP communication, one for responding to the initial connection request sent by the client (socket word A), and one for transferring information between the host and the client (socket B). When the client initiates a TCP connection with the server for the first time, it will specify the first socket of the server and make contact with it. After the contact, the server will generate a new socket B to make a TCP connection with the client, and then Then actually convey the message. And these are actions that occur during the three-way handshake.

client

Although the design of the TCP communication client is different from that of UDP, they have many similarities. First, create two variables that store the IP address and port number of the server; then create a socket object, which is created in a similar way to UDP, but its second parameter is SOCK_STREAM .

ServerIP = '192.168.xx.xx'
ServerPort = 10000
ClientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

The above socket is the socket for the client to communicate externally, but TCP communication requires two parties to shake hands three times to build a TCP connection, which is different from UDP, so we also need to set up a TCP communication channel with the server:

ClientSocket.connect((ServerIP, ServerPort))

After creating this channel, we need to read the information we want to send from the keyboard and send it in the form of bytes. Here we use the send function , which is different from UDP sendto, because the TCP connection is established here, and the transmission The IP and port number may not be appended. We also configure the client to receive feedback from the server, using the recv function. The difference here is that we used the recvfrom function before, because recvfrom can be used for UDP and TCP communication, and recv is often used for TCP communication. After outputting the returned information, we can finally close the socket.

ClientSocket.connect((ServerIP, ServerPort))
print('*'*20+'客户端'+'*'*20)
Content = input('请输入内容:')
ClientSocket.send(Content.encode())
Rec = ClientSocket.recvfrom(2048)
print(Rec[0].decode())
ClientSocket.close()

Service-Terminal

For the server side, TCP communication first also needs to create a socket, which is the socket used for initial contact with the client, that is, the aforementioned socket A. Here we still specify the 10000 port of the server and specify it for the server's socket.

import socket
ServerPort = 10000
ServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ServerSocket.bind(('', ServerPort))

But the difference is that we need to specify this socket as a wait state

ServerSocket.listen(1)

After finishing these, we can start to write socket B used in communication. First, we set socket A to be in the state of waiting for socket B to be created, that is, write a while loop after that: Once the client sends information, we call the accept method of the socket A object, which returns a socket B object and a (IP and port) tuple that records the client data. Then call the method recv of the new socket B to receive the data passed by the client, and finally convert it into bytes and send it back.

while 1:
    Connectsocket, Info = ServerSocket.accept()
    RecMessage = Connectsocket.recv(2048)
    print('接收到'+RecMessage.decode())
    SendMessage = '您发送的'.encode()+RecMessage.decode().encode()+'已接受到'.encode()
    Connectsocket.send(SendMessage)
    Connectsocket.close()

Realize the effect:

client:

Service-Terminal: 


References:

"Computer Networks - A Top-Down Approach Seventh Edition"

Guess you like

Origin blog.csdn.net/m0_61151031/article/details/128780038