Python使用socket实现简单的文
因为工作需要,要在两台设备之间进行压力测试。即A设备不断往B设备发送文件,B设备接收文件后校验文件是否正确接收。
用python的Socket模块写了简单的Server和Client脚本。Server负责监听端口,接收Client发来的文件并做MD5校验,确认接收的文件是否准确无误。Client端负责向Server发送文件及文件的MD5值。
文件名通过Client发送特定字符串提取,文件结束符合通过检测'EOF'字符实现。实际运行过程中,发现总是会有误判,把结束符'EOF'错误写入文件了。希望有大神不吝赐教!!
Socket_Server.py
#!/usr/bin/Python
# -*- coding: utf-8 -*-
# Python: 2.7
# PlatfORM: linux
# Author: wucl(wucl-20@163.com)
# Program: Socket_Server监听网络端口,接收Client发来的文件
# Version: 2.0
# History: 2016.1.28
# 2016.2.1 接收Client发来的文件并做MD5校验
import socket, time, hashlib, os, base64, re
def CalcMD5(fineName, block_size=64 * 1024):
with open(fineName, 'rb') as f:
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
retmd5 = md5.hexdigest()
print(retmd5)
return retmd5
def main(IP, Port, log, error_log):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((IP, Port))
s.listen(12)
print 'Listened on ', socket.gethostname(), Port
reg = re.compile('filename:(.*?):(.*)::::')
while True:
conn, addr = s.accept()
print(time.ctime(), 'Connected from ', addr)
recvd = conn.recv(1024)
if recvd:
ss = reg.findall(recvd)
filename = ss[0][0]
md5 = ss[0][1]
f = open(filename, 'wb')
while True:
data = conn.recv(1024)
if not data:
break
if data == 'EOF':
f.close()
log.write('%s Received %s\n'%(time.ctime(), filename))
log.flush()
if CalcMD5(filename) == md5:
print('%s Received Successfully!\n' %filename)
else:
error_log.write('%s %s Recevied failed\n'%(time.ctime(), filename))
error_log.flush()
print(CalcMD5(filename))
else:
f.write(data)
f.flush()
conn.close()
s.close()
if __name__ == "__main__":
IP = ''
Port = 12345
log = open('log.txt','w+')
error_log = open('error_log.txt','w+')
main(IP, Port, log, error_log)
Socket_Client.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Python: 2.7
# Platform: Linux
# Author: wucl(wucl-20@163.com)
# Program: Socket_Client连接网络端,并向网络端发送文件。
# Version: 2.0
# History: 2016.1.28
# 2016.2.1 Client向Server端发送文件及文件的MD5值
import socket, hashlib
import time, os, base64, os.path
def CalcMD5(fineName, block_size=64 * 1024):
with open(fineName, 'rb') as f:
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
retmd5 = md5.hexdigest()
print(retmd5)
return retmd5
def SendFile(s, filename):
print('Sending %s' % filename)
s.sendall('filename:%s:%s::::'%(filename, CalcMD5(filename)))
f = open(filename, 'rb')
while True:
chunk = f.read(chunksize)
if not chunk:
f.close()
print('%s Successfully Sent %s\n' %(time.ctime(), filename))
break
s.sendall(chunk)
time.sleep(1)
s.sendall('EOF')
s.close()
def main(dirname, IP, Port, MB = 1024):
for filename in os.listdir(dirname):
if os.path.isfile(filename):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, Port))
SendFile(s, filename)
if __name__ == '__main__':
dirname = '/root/test/'
IP = '10.88.106.200'
Port = 12345
MB = 1024
chunksize = int(MB*1024*1024)
main(dirname, IP, Port, MB)
相关文章