由客户端向服务器端发送文件的时候,为解决粘包问题,需要添加一次交互。

服务器端:

# 基于socket的服务器接收文件

import socket
# 建立连接
sk = socket.socket()
sk.bind(('192.168.1.103',8088,))
sk.listen(5)
while True:
    conn,addres = sk.accept()
    print(conn,addres)
    conn.sendall(bytes("welcom to ...",encoding='utf-8'))
# 接收文件大小
    total_size = int(str(conn.recv(1024),encoding='utf-8'))
    # 为解决粘包问题,返回信息确认消息已收到
    conn.sendall(bytes('ok',encoding='utf-8'))
# 接收文件
    has_recv = 0
    f = open("n_ts",'wb')
    while has_recv < total_size:
        data = conn.recv(1024)
        f.write(data)
        has_recv += len(data)
    f.close()

客户端:

# 基于socket的客户端发送文件

import socket
import os

# 建立连接
obj = socket.socket()
obj.connect(("192.168.1.103",8088,))
response = str(obj.recv(1024),encoding='utf-8')
print(response)
# 发送文件大小
file_size = os.stat('ts').st_size
obj.sendall(bytes(str(file_size),encoding='utf-8'))
# 为解决粘包问题,进行一次交互
print(obj.recv(1024))
# 发送文件
with open('ts','rb') as f:
    for line in f:
        obj.sendall(line)