The method of implementing UDP datagram transmission by Python _python

Source: Internet
Author: User

This paper illustrates the method of implementing UDP datagram transmission by Python, which is very practical. Share to everyone for your reference. The specific methods are analyzed as follows:

Service-Side code:

Import socket 
Port = 8081 
s = Socket.socket (socket.af_inet,socket. SOCK_DGRAM) 
#从给定的端口, from any sender, receive UDP datagram 
s.bind ((", port) 
" print ' Waiting on port: ', port while 
True: 
  data,addr = s.recvfrom (1024) 
  #接收一个数据报 (max to 1024 bytes) 
  print ' reciveed: ', data, ' from ', addr 

Client code:

Import socket 
port = 8081 
host = "localhost" 
s = Socket.socket (socket.af_inet,socket. SOCK_DGRAM) 
s.sendto ("Hello World", (Host,port)) 

Results: Run the server first, then run the client,
The Service side prints:

Waiting on port:8081
Reciveed:hello World from (' 127.0.0.1 ', 62644)

Add:
Socket.sendto (string[, flags], address)

The official documents are as follows:

Send data to the socket. The socket should not being connected to a remote socket, since the destination socket was specified by address. The optional Flags argument has the same meaning as for recv () above. Return the number of bytes sent. (The format of address depends in the address family-see above.) The address parameter is a socket in the protocol type. When SOCK_DGRAM, the address structure is a tuple, (host,port) of the format

I hope this article will help you with your Python programming.

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.