Python-implemented udp protocol Server and Client code instance

Source: Internet
Author: User
This article mainly introduces the udp protocol Server and Client code instances implemented by python. For more information, see the following code:
Server:

The code is 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 t (KeyboardInterrupt, SystemExit ):
Raise
Except t:
Traceback. print_exc ()


Client:

The code is 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)
Failed T 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"

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.