Python UDP Server Client

Source: Internet
Author: User

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.


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.