8.5 socket communication based on UDP
Disadvantages: unreliable: transmitting data without acknowledgment, easy loss
udp server
SS = socket 1 () # create a server socket 2 ss.bind () # bind server socket 3 inf_loop: # server infinite loop 4 cs = ss.recvfrom () / ss.sendto () # Dialogue (receive and transmit) . 5 ss.close () # close server socket
udp client
socket = cs () # create a client socket comm_loop: # communication cycle cs.sendto () / cs.recvfrom () # Dialogue (send / receive) cs.close () # close the client socket
8.6 client and server operations (based on UDP)
Server:
Import Socket # address family, based on the network # Datagram Protocol Server = socket.socket (socket.AF_INET, socket.SOCK_DGRAM) server.bind (( ' 127.0.0.1 ' , 8080)) # the address bound to the socket ( 0-65535) 0-1024 to the system used in the while True: client_data, client_addr = server.recvfrom (1,024) # received message, a maximum limit is 1024 Print (client_data.decode ( ' UTF-. 8 ' )) MSG = INPUT ( ' reply S%:% S >>>: ' % (client_addr [0], client_addr [. 1 ])) server.sendto (msg.encode ( ' utf-8'),client_addr)
Client:
import socket client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # 数据报协议 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'))
8.7 Datagram Protocol does not stick package problem
udp The recvfrom is blocked, a recvfrom (x) must only sendinto (y), ended all x bytes of data even if completed, if y> x data is lost, which means that will not stick udp packet, but it will lose the data, unreliable
Each have a UDP packet (information source address and port) message header, so the receiving end to it, it is easy to distinguish the process. That message is a message-oriented communication protected boundaries.
Server:
import socket server=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # 数据报协议 server.bind(('127.0.0.1',8080)) res1,client_addr=server.recvfrom(1) #b'h' print(res1) res2,client_addr=server.recvfrom(2) #b'wo' print(res2) res3,client_addr=server.recvfrom(3) #b'ego' print(res3)
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 ' Egon ' , ( ' 127.0.0.1 ' , 8080))