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 ()