First, Introduction:
Python UDP is no connection, no TCP three handshake, error retransmission mechanism, hair, just send, collect, efficiency than TCP high, applied to the data frame is not high, such as video, audio transmission
Second, the realization process:
The server-side process is as follows:
1. Creating a UDP socket
2. Bind an interface to allow the client to connect
3. Acceptance of data
The client process is as follows:
1. Create a socket
2. Send and receive datagrams
Third, the 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 ' ... received 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) #创建socket
While True:
Data=raw_input (' > ')
If not data:
Break
Udpclientsocket.sendto (data,address) #发送数据
Data,addr=udpclientsocket.recvfrom (2048)
Print data
Udpclientsocket.close ()
If __name__== "__main__":
UdpClient ()
UDP implementation of Python network programming