Python network programming-UDP implementation, python network programming udp

Source: Internet
Author: User

Python network programming-UDP implementation, python network programming udp
I. Introduction:

Python udp is connectionless, without three-way handshake of TCP, error retransmission mechanism, sending only sending, receiving only receiving, the efficiency is higher than TCP, used in places where the data frame is not high, for example, video and audio transmission

II. Implementation Process:

The server process is as follows:

1. Create a UDP SOCKET

2. bind an interface to connect the client

3. Accept data


The client process is as follows:
1. Create a socket

2. send and receive data packets


Iii. Code Implementation

1. server side:

Import socket
From time import ctime

Def udpServer ():
Buffer= 2048
Address = ("127.0.0.1", 8080)
Udpsock = socket. socket (socket. AF_INET, socket. SOCK_DGRAM)
Udpsock. bind (address)
While True:
Print "wait for message ..."
Data, addr = udpsock. recvfrom (buffer)
Udpsock. sendto ('[% s] % s' % (ctime (), data), addr)
Print '... stored ed from and retuned to:', addr
Udpsock. close ()

If _ name __= = "_ main __":
UdpServer ()

2. Client:

Import socket
Def udpClient ():
Address = ("localhost", 8080)
UdpClientSocket = socket. socket (socket. AF_INET, socket. SOCK_DGRAM) # create a socket
While True:
Data = raw_input ('> ')
If not data:
Break
UdpClientSocket. sendto (data, address) # send data
Data, addr = udpClientSocket. recvfrom (2048)
Print data
UdpClientSocket. close ()
 
If _ name __= = "_ main __":
UdpClient ()




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.