3.UDP服务器端代码
from socket import *
print '***** Now starting server *****'
Host=''
Port=12306
Buffsize=1024
Addr=(Host,Port)
ServerSocket=socket(AF_INET,SOCK_DGRAM) #初始化一个UDP套接字
ServerSocket.bind(Addr)
print '* Initing connection...'
while True:
print '* Now waiting for message...\n'
data , addr=ServerSocket.recvfrom(Buffsize)
print '* Get message from',addr
ServerSocket.sendto('Server: Message [ %s ] send successfully' % data,addr)
#返回信息给客户端
print '* Client : %s' %data
ServerSocket.close()
4.UDP客户端代码
from socket import *
print '***** Now starting client *****'
Host='localhost'
Port=12306
Buffsize=1024
Addr=(Host,Port)
ClientSocket=socket(AF_INET,SOCK_DGRAM) #初始化一个TCP套接字
while True:
data=raw_input('> ') #从控制台输入消息
if not data:
break
ClientSocket.sendto(data,Addr) #传输UDP消息给服务器
data,addr=ClientSocket.recvfrom(Buffsize) #获取UDP消息
if not data:
break
print data
ClientSocket.close()
效果图: