server:
from socket import *
from time import ctime
HOST = ''
PORT = 8888
BUFSIZ = 1024
ADDRESS = (HOST, PORT)
udpServerSocket = socket(AF_INET, SOCK_DGRAM)
udpServerSocket.bind(ADDRESS)
print("waiting for message...")
while True:
data, addr = udpServerSocket.recvfrom(BUFSIZ)
#print("Recv data:", data.decode('utf-8'))
print(data.decode('utf-8'))
content = '[%s] %s' % (bytes(ctime(), 'utf-8'), data.decode('utf-8'))
udpServerSocket.sendto(content.encode('utf-8'), addr)
#print('...received from and returned to:', addr)
udpServerSocket.close()
client:
#/usr/bin/env/python
#coding=utf-8
import sys,re,time,os
from socket import *
HOST = '127.0.0.1'
PORT = 8888
BUFSIZ = 1024
INTERVAL_TIME = 3
ADDRESS = (HOST, PORT)
udpClientSocket = socket(AF_INET, SOCK_DGRAM)
netcard = '/proc/net/dev'
def checkfile(filename):
if os.path.isfile(filename):
pass
else:
f = open(filename, 'w')
f.write('0')
f.close()
def get_net_data():
nc = netcard or '/proc/net/dev'
fd = open(nc, "r")
netcardstatus = False
for line in fd.readlines():
if line.find("eth1") > 0:
netcardstatus = True
field = line.split()
#print(field)
recv = field[0].split(":")[1]
if(len(recv) == 0):
recv = field[1]
send = field[9]
else:
send = field[8]
if not netcardstatus:
fd.close()
print('Please setup your netcard')
sys.exit()
fd.close()
return (float(recv), float(send))
def monfirst(filename):
nowtime = time.strftime('%m-%d %H:%M',time.localtime(time.time()))
sec = time.localtime().tm_sec
if nowtime == '01-01 00:00':
if sec < 10:
f = open(filename, 'w')
f.write('0')
f.close()
def net_loop():
(recv, send) = get_net_data()
while True:
time.sleep(INTERVAL_TIME)
(new_recv, new_send) = get_net_data()
recvdata = (new_recv - recv) / 1024 / INTERVAL_TIME
senddata = (new_send - send) / 1024 / INTERVAL_TIME
#totaltrans += int(recvdata)
#totaltrans += int(senddata)
data = ("rxkB/s: %f, txkB/s: %f"%(recvdata, senddata))
udpClientSocket.sendto(data.encode('utf-8'), ADDRESS)
#udpClientSocket.sendto("aaaaa".encode('utf-8'), ADDRESS)
#print("rx: %f"%(recvdata))
#print("tx: %f"%(senddata))
recv = new_recv
send = new_send
if __name__ == "__main__":
net_loop()
使用方法:
服务端:
python3 udp_server.py
客户端:
python3 udp_client.py
客户端配置:
HOST = ‘127.0.0.1’ # 目的ip
PORT = 8888 # 目的端口
BUFSIZ = 1024 # 可发送的最大buff
INTERVAL_TIME = 3 # 间隔时间(秒)