# -*- coding: UTF-8 -*-
import os
import socket
# TCP/IP协议, tcp ,如果不填写就是默认这个
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((‘localhost‘, 9999))
server.listen()
while True: # 可以接受多个客户端
conn, addr = server.accept()
print(‘new conn‘, addr)
while True:
cmd_res = conn.recv(1024)
if not cmd_res: # 防止当接受的客户端数据为空时,程序卡掉
print(‘client has lost...‘)
break
else:
# 获取命令和文件名
cmd, filename = cmd_res.decode().split()
print(cmd, filename)
if os.path.isfile(filename): # 判断文件是否存在
# 文件大小
file_size = os.stat(filename).st_size
# 发送文件大小
conn.send(str(file_size).encode(‘utf-8‘))
# 等待客户端确认
conn.recv(1024)
# 打开文件
f = open(filename, ‘rb‘)
for line in f:
conn.send(line)
f.close()