The TCP transmission data is reliable, and the data sent and received needs to be confirmed. If it is not confirmed, it will be resent. Using data stream mode, can not send empty data
UDP transmission data is unreliable, no matter whether the other party receives it or not, the advantage is that there is no need for three-way handshake, and the efficiency is high. In datagram mode, empty data can be sent. UDP must be sent and received.
UDP protocol will not stick packets
server:
from socket import * server =socket(AF_INET,SOCK_DGRAM) #Datagram protocol server.bind(( ' 127.0.0.1 ' ,8090)) #Binding port, # server.listen (5)If UDP has no connection, there is no listening # server.accept()UDP does not need to establish a connection while True: #communication loop data,client_addr=server.recvfrom(1024 ) print (data) server.sendto(data.upper(),client_addr) server.close()
client:
from socket import * client=socket(AF_INET,SOCK_DGRAM) while True: msg=input('>>:').strip() client.sendto(msg.encode( " utf-8 " ),( ' 127.0.0.1 ' ,8090)) #Specify who to send data to, server_addr =client.recvfrom(1024 ) print (data) client.close()
Network queries (ntp, dns), chat messages, etc. are all implemented through UDP