(python) socket based on UDP protocol communication

UDP, User Datagram Protocol. It is connectionless, message-oriented, and provides high-efficiency services, but this service does not guarantee the reliability of data transmission. Data may be lost or duplicated during transmission, and the order of data reception cannot be guaranteed. It does not use the merge optimization algorithm. Due to the one-to-many mode supported by UDP, the socket buffer (skbuff) of the receiving end adopts a chain structure to record each arriving UDP packet. In each UDP packet, there are The message header (message source address, port, etc.) is included, so that it is easy to perform partition processing for receiving. Message-oriented communication has message protection boundaries.

Client:

import socket

client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # datagram protocol

while True:
    msg=input('>>>: ').strip()
    client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
    res,server_addr=client.recvfrom(1024)
    print(res.decode('utf-8'))

Server:

import socket

server=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # datagram protocol
server.bind(('127.0.0.1',8080))

while True:
    client_data,client_addr=server.recvfrom(1024)
    server.sendto(client_data.upper(),client_addr)

Because it is not connected, and there is no semi-connection pool. So there can be multiple clients communicating with it at different times. Because the processing speed of the computer is fast, it gives the illusion of concurrent processing.

Because the UDP packet has a header, which clearly distinguishes the boundary of the message, it does not generate sticky packets.

Client:

import socket

client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # datagram protocol

client.sendto(b'hello',('127.0.0.1',8080))
client.sendto(b'world',('127.0.0.1',8080))
client.sendto(b'monicx',('127.0.0.1',8080))

Server:

import socket

server=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # datagram protocol
server.bind(('127.0.0.1',8080))

res1,client_addr1=server.recvfrom(1024)
print(res1)

res2,client_addr2=server.recvfrom(1024)
print(res2)

res3,client_addr3=server.recvfrom(1024)
print(res3)

The result of running is that there is no sticky package:






Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324815574&siteId=291194637