Udp:
TCP is to establish a reliable connection, and both sides of the communication can send data in the form of a stream. The relative tcp,udp is a non-connection oriented protocol.
When using the UDP protocol, you do not need to establish a connection, just need to know the other side's IP address and port number, you can directly send packets. But I don't know if I can get there.
Although the transmission of data with UDP is unreliable, its advantage is that it is faster than TCP, and the UDP protocol can be used for data that does not require reliable arrival.
Service-Side program:
# 1 Create socket and bind to local address socket,bing# 2 receive data directly from buffer. Recvfrom (), this function accepts data, and #sender address (host number, port number), of course, can also send data to the client, with #sendto (data,addr)# 3 Close socket Close ()# pseudo code:ss=socket () # Create socket ss.bind () # bind inf_loop: # Infinite loop ss.recvfrom ()/sendto () # Dialog ss.close () # Close Socket
#my program:ImportSockets=Socket.socket (Socket.af_inet,socket. SOCK_DGRAM) S.bind (('127.0.0.1', 9998))Print('Bind up on 9999 ...') while1: Data,addr= S.recvfrom (1024) Print('Receive from%s:%s .....'%ADDR)#addr is a tuple ' 127.0.0.1 ': 9999S.sendto (b'hello,%s'+DATA,ADDR)#s.sendto (data[, flags], address) #or S.sendto (' Hello,%s! '% data.decode (' Utf-8 ')). Encode (' Utf-8 '), addr) #or s.sendto (b ' ddddddd ', addr)
Client program:
# 1 Create socket, socket# 2 Enter loop, send receive Data sendto, Recvfrom# 3 Close socket Close ()# pseudo code:cs=socket () # Create comm_loop: # Loop receive send # Dialog cs.close () # Close
#my program:ImportSockets=Socket.socket (Socket.af_inet,socket. SOCK_DGRAM) fordata111inch[b'Chenhang'B'Wangyadan'B'Wust'B'HUSTWB']: S.sendto (data111, ('127.0.0.1', 9998)) Print(S.recv (1024x768). Decode ('Utf-8') ) S.close ()
Socket local analog UDP server + client (iii)