This paper illustrates the method of implementing UDP datagram transmission by Python, which is very practical. Share to everyone for your reference. The specific methods are analyzed as follows:
Service-Side code:
Import socket
Port = 8081
s = Socket.socket (socket.af_inet,socket. SOCK_DGRAM)
#从给定的端口, from any sender, receive UDP datagram
s.bind ((", port)
" print ' Waiting on port: ', port while
True:
data,addr = s.recvfrom (1024)
#接收一个数据报 (max to 1024 bytes)
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))
Results: Run the server first, then run the client,
The Service side prints:
Waiting on port:8081
Reciveed:hello World from (' 127.0.0.1 ', 62644)
Add:
Socket.sendto (string[, flags], address)
The official documents are as follows:
Send data to the socket. The socket should not being connected to a remote socket, since the destination socket was specified by address. The optional Flags argument has the same meaning as for recv () above. Return the number of bytes sent. (The format of address depends in the address family-see above.) The address parameter is a socket in the protocol type. When SOCK_DGRAM, the address structure is a tuple, (host,port) of the format
I hope this article will help you with your Python programming.