首页 > 代码库 > 用python做UDP连接

用python做UDP连接

写个客户端

#!/usr/bin/env python
from socket import *
HOST = '10.2.167.115'
PORT = 20001
BUFSIZE = 1024
ADDR = (HOST, PORT)
udpClientSock = socket(AF_INET, SOCK_DGRAM)
while True:
    data = raw_input('Enter the message you want to send >')
    if not data:
        break
    udpClientSock.sendto(data, ADDR)发送给服务端
    data, ADDR = udpClientSock.recvfrom(BUFSIZE)接收服务端信息
    if not data:
        break
    print data
udpClientSock.close()





写个服务端



#!/usr/bin/env python
# -*- coding:UTF-8 -*-


from socket import *
from time import ctime

HOST = ''
PORT = 20001监控端口
BUFSIZE = 1024缓冲区大小
ADDR = (HOST, PORT)
udpSerSock = socket(AF_INET, SOCK_DGRAM)
udpSerSock.bind(ADDR)
while True:
    print 'waiting for message...'
    data, addr = udpSerSock.recvfrom(BUFSIZE)
    udpSerSock.sendto('[%s] %s' % (ctime(), data), addr)给客户端发送信息
    print'received from %s >> %s' % (addr, data)
udpSerSock.close()

这个udp连接可以用于测速。在客户端记录开始和结束时间。再除以2可以估计网络耗时。忽略服务器响应时间

用python做UDP连接