Python is a simple udp server and Client example. The server needs to be started first and then the client starts.
#-*-Coding: cp936 udp Server first-*-zdt
Import socket, time
Import random
L Port = 8013
Rport = 8012
Host = "localhost"
S = socket. socket (socket. AF_INET, socket. SOCK_DGRAM)
# Receive UDP datagram from any sender from a given port
S. bind (host, Lport ))
Print 'Bind to the ', host, Lport
While True:
Try:
Data, addr = s. recvfrom (1024)
# Receive a datagram (up to 1024 bytes)
Print 'stored ed: ', data, "from", addr
S. sendto (data, (host, Rport ))
If data = 'exit ':
Break
Except t:
Print "error in client ..."
Break
S. close
Msg = raw_input ("Press any key to exit ...")
#-*-Coding: After cp936 udp Client is started-*-zdt
Import socket, time, random
L Port = 8012
Rport = 8013
Host = "localhost"
S = socket. socket (socket. AF_INET, socket. SOCK_DGRAM)
S. bind (host, Lport ))
Print 'Bind to the ', host, Lport
I = 1
While True:
Try:
# Msg = raw_input ('Type your information \ n ')
Msg = 'hello'
If (msg = 'q' or I> 20 ):
S. sendto ('exit ', (host, Rport ))
Break
Else:
S. sendto (str (I) + ":" + str (random. uniform (1,100), (host, Rport ))
# Time. sleep (1)
Data, addr = s. recvfrom (1024)
Print I, ': stored ed:', data, "from", addr
I = I + 1
Except t:
Print "error at sever, the serer didn't start ..."
Break
S. close
Raw_input ('Press any key to exit ....')
**************************************** ****************************************
Python is a simple udp server and Client example. The server needs to be started first and then the client starts.