一个简单的文件上传服务器和客户端
服务器
# -----------------------
# __Author : tyran
# __Date : 17-11-16
# -----------------------
# 文件上传服务器
import socket
import os
def get_listen_socket(addr_port: tuple, wait_num=5, is_block=True):
"""
获取监听套接字
:param addr_port:必须为tuple类型,(‘ip address’, port_number)
:param wait_num: 允许等待人数
:param is_block: 是否阻塞
:return: 返回监听套接字
"""
sk = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
sk.bind(addr_port)
sk.setblocking(is_block)
sk.listen(wait_num)
return sk
def save_file(file, f_data):
with open(file, 'wb') as fd:
fd.write(f_data)
if __name__ == '__main__':
listen_socket = get_listen_socket(('127.0.0.1', 8888), 2)
while True:
client_socket, client_address = listen_socket.accept()
# 获取上传的信息,文件大小,文件名,我规定了上传格式“文件名|文件大小”
file_name, file_size = str(client_socket.recv(1024), encoding='utf-8').strip().split('|')
client_socket.send(bytes('update begin', encoding='utf-8'))
# 开始接收上传数据
file_data = bytes()
file_size = int(file_size)
while file_size:
data = client_socket.recv(1024)
file_size -= len(data)
file_data += data
save_file(os.path.join(os.path.dirname(__file__), 'image', file_name), file_data)
# -----------------------
# __Author : tyran
# __Date : 17-11-16
# -----------------------
import socket
import os
def connect_server(addr_port: tuple, filename):
sk = socket.socket()
sk.connect(addr_port)
file_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), filename)
file_size = os.stat(file_path).st_size
sk.send(bytes(filename+'|'+str(file_size), encoding='utf-8'))
print(str(sk.recv(1024), encoding='utf-8'))
with open(file_path, 'rb') as fd:
for line in fd:
# print(line)
sk.send(line)
sk.close()
if __name__ == '__main__':
connect_server(('127.0.0.1', 8888), 'new_web.jpg')