Python implementation of UDP protocol server and client code instance _python

Source: Internet
Author: User
Directly on the code:
Server End:
Copy Code code as follows:

#!/usr/bin/env python
# UDP Echo server-udpserver.py
Import socket, Traceback

Host = '
Port = 54321

s = socket.socket (socket.af_inet, socket. SOCK_DGRAM)
S.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1)
S.bind (host, Port)

While 1:
Try
message, address = S.recvfrom (8192)
print ' Got data from ', Address, ': ', message
S.sendto (message, address)
Except (Keyboardinterrupt, Systemexit):
Raise
Except
Traceback.print_exc ()

Client side:
Copy Code code as follows:
1 #!/usr/bin/env python
# UDP client-udpclient.py
Import socket, sys

Host = Sys.argv[1]
Textport = sys.argv[2]

s = socket.socket (socket.af_inet, socket. SOCK_DGRAM)
Try
Port = Int (textport)
Except ValueError:
Port = socket.getservbyname (textport, ' UDP ')
S.connect (host, Port)
While 1:
Print "Enter data to transmit:"
data = Sys.stdin.readline (). Strip ()
S.sendall (data)
Print "Looking for replies; Press CTRL-C or Ctrl-break to stop. "
BUF = S.RECV (2048)
If not Len (BUF):
Break
Print "Server replies:",
Sys.stdout.write (BUF)
print "\ n"
Related Article

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.