udp protocol transmission

Server code:

. 1  from Socket Import *
 2  
. 3 udp_server = Socket (AF_INET, SOCK_DGRAM)   # datagram sockets 
. 4 udp_server.bind (( ' 127.0.0.1 ' , 8080 ))
 . 5  the while True:
 . 6      Data = udp_server.recvfrom (1024)    # accepted that a tuple, the tuple of the first parameter byte is received, the second parameter is the address of the sender 
. 7      Print (Data)
 . 8      Print (Data [0] .decode ())

Client code:

. 1  from Socket Import *
 2  
. 3 udp_client = Socket (AF_INET, SOCK_DGRAM)
 . 4 udp_client.sendto ( ' Hello, Python ' .encode (), ( ' 127.0.0.1 ' , 8080))   # UDP transmission for a tuple, the first parameter byte, the second argument is the address of the recipient

tcp and udp difference

null byte can accept udp recvfrom () can not accept null tcp recv ()

udp can be achieved simultaneously serve multiple concurrent clients

Time to achieve acquisition program server:

 1 from socket import *
 2 import time
 3 
 4 udp_server = socket(AF_INET, SOCK_DGRAM)
 5 udp_server.bind(('127.0.0.1', 8080))
 6 while True:
 7     data, addr = udp_server.recvfrom(1024)
 8     # print(data.decode())
 9     if not data:
10         fm = '%Y-%m-%d %X'
11     else:
12         fm = data.decode()
13     udp_server.sendto(time.strftime(fm).encode(), addr)

Server:

. 1  from Socket Import *
 2  
. 3 upp_client = Socket (AF_INET, SOCK_DGRAM)
 . 4  the while True:
 . 5      MSG = INPUT ( ' Enter Format: ' )
 . 6      upp_client.sendto (msg.encode (), ( ' 127.0.0.1 ' , 8080 ))
 . 7      Data, addr = upp_client.recvfrom (1024 )
 . 8      Print ( ' server information is sent, ' , data.decode ())

 

Guess you like

Origin www.cnblogs.com/ch2020/p/12524794.html