Python implements the method of udp datagram transmission
- 2020-04-02 14:11:17
- OfStack
This article illustrates the method of UDP datagram transmission in Python, which is of great practical value. Share with you for your reference. Specific methods are analyzed as follows:
Server code:
import socket
port = 8081
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
# Receive from any sender on a given port UDP The datagram
s.bind(("",port))
print 'waiting on port:',port
while True:
data,addr = s.recvfrom(1024)
# Receive a datagram ( To the largest 1024 byte )
print 'reciveed:',data,"from",addr
Client code:
import socket
port = 8081
host = "localhost"
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.sendto("hello world",(host,port))
Result: run the server first, then the client,
The server prints out:
waiting on port: 8081
reciveed: hello world from ('127.0.0.1', 62644)
Supplement:
Sockets sendto (string [, flags], address)
The official document is as follows:
Send data to the socket. The socket should not be connected to a remote socket. Since the destination socket is specified by address.the optional flags argument has the same meaning as for recv() over.return the number of bytes sent Address family -- see above.)address parameter when the protocol type is socket.sock_dgram, the structure of address is a tuple, (host,port) format
I hope this article has helped you with your Python programming.