Python网络编程(三)-基于tcp协议实现文件传输(基础版)

server.py

#服务端接收
import json
import socket

sk = socket.socket()
sk.bind(('127.0.0.1',9000))
sk.listen()

conn,addr = sk.accept()
msg = conn.recv(1024).decode('utf-8')
msg = json.loads(msg)
print(msg['filename'],msg['filesize'])

with open(msg['filename'],mode='wb') as f:
    content = conn.recv(msg['filesize'])
    print('--filelen',len(content))
    f.write(content)

conn.close()
sk.close()
server端代码

client.py

#客户端发送
import os
import json
import socket

sk = socket.socket()
sk.connect(('127.0.0.1',9000))

#需要发送文件名,文件大小

abs_path = r'E:\project\tcp-testfile'
# os.path模块获取文件名
filename = os.path.basename(abs_path)
# os.path模块获取文件大小
filesize = os.path.getsize(abs_path)
dic = {'filename':filename,'filesize':filesize}
#  网编中传输数据,常用的是json类型
str_dic = json.dumps(dic)
sk.send(str_dic.encode('utf-8'))

with open(abs_path,mode='rb') as f:
    content = f.read()
    sk.send(content)

sk.close()
client端代码

 

posted @ 2020-12-05 20:31  精灵中的二丫  阅读(274)  评论(0编辑  收藏  举报