客户端
"""
file: send.py
socket client
"""
import socket
import os
import sys
import struct
import time
def socket_client():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 6666))
except socket.error as msg:
print msg
sys.exit(1)
print s.recv(1024)
filepath = raw_input('please input file path: ')
if os.path.isfile(filepath):
fileinfo_size = struct.calcsize('128sl')
fhead = struct.pack('128sl', os.path.basename(filepath),
os.stat(filepath).st_size)
s.send(fhead)
print 'client filepath: {0}'.format(filepath)
fp = open(filepath, 'rb')
while 1:
data = fp.read(1024)
if not data:
print '{0} file send over...'.format(filepath)
break
s.send(data)
fileinfo0_size = struct.calcsize('128sl')
buf0 = s.recv(fileinfo0_size)
if buf0:
filename0, filesize0 = struct.unpack('128sl', buf0)
fn0 = filename0.strip('\00')
new_filename0 = os.path.join('./', 'new1_' + fn0)
fp = open(new_filename0, 'wb')
recvd_size0=0
while not recvd_size0 == filesize0:
if filesize0 - recvd_size0 > 1024:
data1 = s.recv(1024)
recvd_size0 += len(data1)
else:
data1 = s.recv(filesize0 - recvd_size0)
recvd_size0 = filesize0
fp.write(data1)
s.close()
if __name__ == '__main__':
socket_client()
服务端
import socket
import threading
import time
import sys
import os
import struct
import cv2
def socket_service():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', 6666))
s.listen(10)
except socket.error as msg:
print msg
sys.exit(1)
print 'Waiting connection...'
while 1:
conn, addr = s.accept()
t = threading.Thread(target=deal_data, args=(conn, addr))
t.start()
def deal_data(conn, addr):
print 'Accept new connection from {0}'.format(addr)
conn.send('Hi, Welcome to the server!')
while 1:
fileinfo_size = struct.calcsize('128sl')
buf = conn.recv(fileinfo_size)
if buf:
filename, filesize = struct.unpack('128sl', buf)
print filename
fn = filename.strip('\00')
new_filename = os.path.join('./', 'new_' + fn)
print 'file new name is {0}, filesize if {1}'.format(new_filename,
filesize)
recvd_size = 0
fp = open(new_filename, 'wb')
print 'start receiving...'
while not recvd_size == filesize:
if filesize - recvd_size > 1024:
data = conn.recv(1024)
recvd_size += len(data)
else:
data = conn.recv(filesize - recvd_size)
recvd_size = filesize
fp.write(data)
fp.close()
print 'end receive...'
break
img=cv2.imread(new_filename)
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
new_filename1 = os.path.join('./', 'new0_' + fn)
cv2.imwrite(new_filename1,gray)
new_filename1_size = struct.calcsize('128sl')
fhead1 = struct.pack('128sl', os.path.basename(new_filename1),
os.stat(new_filename1).st_size)
conn.send(fhead1)
fp1=open(new_filename1, 'rb')
print 'start sending...'
while 1:
data0 = fp1.read(1024)
if not data0:
print '{0} file send over...'.format(new_filename1)
break
conn.send(data0)
conn.close()
if __name__ == '__main__':
socket_service()