python--Network Programming-----Socket based on UDP protocol

Source: Internet
Author: User

Service side:

1  fromSocketImport*2 3Server =socket (af_inet, SOCK_DGRAM)4Server.bind (('127.0.0.1', 8080))5 6  whileTrue:7data, client_addr = Server.recvfrom (1024)8     Print(data, client_addr)9 Ten server.sendto (Data.upper (), client_addr) One  AServer.close ()

Client:

1  fromSocketImport*2 3Client =socket (af_inet, SOCK_DGRAM)4 5  whileTrue:6msg = input (">>:"). Strip ()7Client.sendto (Msg.encode ('Utf-8'), ('127.0.0.1', 8080))8 9data, server_addr = Client.recvfrom (1024)Ten     Print(data, SERVER_ADDR) One  AClient.close ()

Start the server first, then start the client, enter the lowercase ABC in the client,

The client runs the result as:

1 >>: ABC2 b'abc' ('127.0.0.1' , 8080)3 >>:

The server run results are:

1 b'abc' ('127.0.0.1', 55255)

This implements a simple socket program based on the UDP protocol.

UDP protocol-based sockets can be empty:

When the client input is empty,

The client runs the result as:

1 >>:2 b' ('127.0.0.1', 8080)3 >>:4 b' ('127.0.0.1', 8080)  5 >>:

UDP even if the sending data is empty, but UDP is the datagram protocol, the datagram also contains IP port information, so that the datagram is not empty

python--Network Programming-----Socket based on UDP protocol

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.