In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains the "Python network programming UDP protocol analysis", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Python network programming UDP protocol analysis"!
Overview of UDP Protocol
UDP protocol-User Datagram Protocol, that is, user packet protocol, UDP protocol is connectionless, unreliable, efficient data transmission protocol.
UDP protocol has the advantages of low overhead, high speed and no connection.
Disadvantages of UDP protocol: no acknowledgement retransmission and sorting, no flow control, no error recovery.
UDP protocol is a message-oriented transmission protocol, which neither splits nor merges the message, but adds a header to the message and then hands it down to the IP layer. Don't retransmit when you find an error, simply throw away the error message or provide a warning to the application.
UDP protocol is widely used in multimedia applications that emphasize data transmission rate, such as network chat, online video, online games, real-time monitoring, routing table modification in routing protocols and so on.
The TCP protocol requires retransmission when it encounters packet loss or error, which results in a significant reduction in the transmission rate.
UDP protocol does not require retransmission when it encounters packet loss or error, because a new message will replace it within a few seconds after a message is lost, so the transmission rate of UDP protocol is much higher than that of TCP protocol.
The application needs to customize the application layer protocol to deal with packet loss, error and disorder.
Writing UDP applications requires careful consideration of the appropriate message length:
The LAN maximum transmission unit (Maximum Transmission Unit,MTU) defaults to 1500 bytes.
The UDP protocol header is 8 bytes and the IP layer protocol header is 20 bytes.
The recommended length of a single message is 1024 bytes, and the maximum length must not exceed 65507 bytes (the total length of the message plus header must not exceed 65535 bytes).
In a better network environment, the length of Times text and the suggestion of receiving cache should be larger, which can reduce the probability of packet loss caused by untimely message reception.
Udp protocol server
Create an instance of socket.
Sk = socket.socket (type=socket.SOCK_DGRAM)
Note: type=socket.SOCK_DGRAM is the specified keyword parameter, not "default type=". This parameter is used to specify the use of the udp protocol.
Bind ip and port.
Sk.bind (('127.0.0.1))
Description: this method has a parameter of type tuple (the first element of the tuple is IP, and the second element is port). No return value.
Receive messages from the UDP client.
Message,addrress = sk.recvfrom (1024)
Description: the parameter of this method is the length of the received message. The return value is the tuple, the first item of the tuple is the message, and the second item is the ip and port.
Send a message to the UDP client.
Sk.sendto (message,address)
Note: the method has two parameters, the first parameter is the message to be sent, which must be bytes, and the second parameter is the tuple (the first element of the tuple is IP, and the second element is port). The return value is the number of bytes sent.
Udp protocol client
Create an instance of socket.
Sk = socket.socket ()
Send a message to the UDP server.
Sk.sendto (message.encode (), ('127.0.0.1))
Note: the method has two parameters, the first parameter is the message to be sent, which must be bytes, and the second parameter is the tuple (the first element of the tuple is IP, and the second element is port). The return value is the number of bytes sent.
Receive messages from the UDP server.
Message = sk.recv (1024) .decode ()
Description: the parameter of this method is the length of the received message. The return value is the message.
Case: udp protocol chat room
Server side
Import socketHOST = '127.0.0.1' # IP address PORT = 50007 # Port max_connect = 5def main (): accounts = {} with socket.socket (type=socket.SOCK_DGRAM) as sk:sk.bind ((HOST, PORT)) while True:msg, address = sk.recvfrom (1024) rev = msg.decode (). Split ('| |') accounts [rev [0]] = addressif rev [1] in accounts:sk.sendto (msg) Accounts [rev [1]]) if _ _ name__ = "_ _ main__": main ()
Note: this is a UDP protocol simple chat room server model. When the server receives a message from the client, it records the ip, port and account number of the client, and updates it to the dictionary. When the message sent to the target account is in the dictionary, the message will be forwarded to the target account, thus realizing the multi-person chat function.
Note: the code currently does not cache the message, which will be discarded when the destination to be sent is not online.
Client
Import socketfrom threading import Threadimport sysHOST = '127.0.0.1' # IP address PORT = 50007 # port class Transceiver:def _ _ init__ (self, conn, server, account: str, target: str Buffer: int = 1024)-> None:self.conn = conn # socket instance self.server = server # destination ip and port self.buffer = buffer # cache size self.path = (account +'| |'+ target +'|'). Encode () # own account def send (self Message: str)-> None: "send message" if type (message) is str: # determine the message type message = message.encode () # convert the message to bytes type The default parameter is utf8 encoding self.conn.sendto (self.path + message, self.server) # send message def recv (self): "" receive message "message, _ = self.conn.recvfrom (self.buffer) message = message.decode ('utf8'). Split (' |') return message [1], message [2] # returns the message string def main (): def send (m, message): m.send (message) def recv (m): while True:try:source Data = m.recv () print (f' received a message from "{source}": {data}') except:passwith socket.socket (type=socket.SOCK_DGRAM) as sk:account = input ("Please enter your account:") target= input ("Please enter the account you want to chat:") m = Transceiver (sk, (HOST, PORT), account, target) t = Thread (target=recv, args= (m) ) t.setDaemon (True) t.start () while True:message = input ('Please enter the message you want to send:') if not message:continueif message = ='q' or message = = 'Q':sys.exit (0) Thread (target=send, args= (m, message)). Start () if _ name__ = = "_ main__": main ()
Note: this is a simple chat room client model of the udp protocol. When the client logs in, it first enters its own account and the other party's account, and then enters the loop to enter the message sent to the other party's account, and opens a sub-harvest process to receive the message forwarded by the server.
Thank you for your reading, the above is the content of "Python network programming UDP protocol analysis". After the study of this article, I believe you have a deeper understanding of the Python network programming UDP protocol analysis, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.