目录
服务端
1.创建TCP套接字,绑定端口
2.设置监听
3.接收客户端传输的文件名信息并解码
4.将文件发送到客户端
5.关闭客户端套接字
代码
import socket
import os
import sys
import struct
def socket_img():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
s.bind(('192.168.9.138', 6666))
s.listen(10)
except socket.error as msg:
print(msg)
sys.exit(1)
print('Wait for Connection.................')
while True:
sock, addr = s.accept()
deal_img(sock, addr)
def deal_img(sock,addr):
print('Accept connection from {0}'.format(addr))
while True:
file_sizes = struct.calcsize('128sq')
buf = sock.recv(file_sizes)
if buf:
filename, filesize = struct.unpack('128sq', buf)
f = filename.decode().strip('\x00')
new_file = os.path.join('./', 'new_' + f)
recvd_size = 0
fp = open(new_file, 'wb')
while not recvd_size == filesize:
if filesize - recvd_size > 1024:
data = sock.recv(1024)
recvd_size += len(data)
else:
data = sock.recv(1024)
recvd_size = filesize
fp.write(data)
fp.close()
sock.close()
break
if __name__ == '__main__':
socket_img()
客户端
1.创建TCP套接字,绑定端口
2.连接服务端
3.输入要下载的文件
4.将文件名编码,并发送到服务端
5.接收服务端返回的数据
6.关闭套接字
代码
import socket
import os
import sys
import struct
def sock_client_image():
while True:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.10.215', 6666))
except socket.error as msg:
print(msg)
print(sys.exit(1))
filepath = input('input the file:')
fhead = struct.pack(b'128sq', bytes(os.path.basename(filepath), encoding='utf-8'),
os.stat(filepath).st_size)
s.send(fhead)
fp = open(filepath, 'rb')
while True:
data = fp.read(1024)
if not data:
print('{0} send over...'.format(filepath))
break
s.send(data)
s.close()
if __name__ == '__main__':
sock_client_image()