客户端

import struct
import json
from socket import * client=socket(AF_INET,SOCK_STREAM)
# client.connect(('121.36.98.49',8822))
client.connect(('127.0.0.1',8811)) while True:
cmd=input('请输入命令(dw or up +文件)>>:').strip()
if len(cmd) == 0:continue
client.send(cmd.encode('utf-8')) # 接收端
# 1、先手4个字节,从中提取接下来要收的头的长度
x=client.recv(4)
print(x)
header_len=struct.unpack('i',x)[0] # 2、接收头,并解析
json_str_bytes=client.recv(header_len)
json_str=json_str_bytes.decode('utf-8')
header_dic=json.loads(json_str)
print(header_dic)
total_size=header_dic["file_size"] # 3、接收真实的数据
recv_size = 0
while recv_size < total_size:
recv_data=client.recv(1024)
recv_size+=len(recv_data)
with open(f"my{header_dic['file_name']}",'wb') as f :
f.write(recv_data)
else:
print()

服务端

import struct
import json
from socket import * server = socket(AF_INET, SOCK_STREAM)
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
server.bind(('127.0.0.1',8811))
# server.bind(('0.0.0.0',8812))
server.listen(5) while True:
conn, client_addr = server.accept() while True:
try:
cmd = conn.recv(1024)
if len(cmd) == 0: break
cmd = cmd.decode('utf-8')
cmd = cmd.split(',')
print(cmd[0],cmd[1])
if cmd[0] == 'up':
pass # 执行上传
elif cmd[0] == 'dw': # 执行下载
print('开始传送')
with open(f'/hz/{cmd[1]}','rb') as f :
file_data = f.read()
print(file_data)
print('传送完毕')
file_size = len(file_data)
header_dic = {
"mode": cmd[0],
'file_name':cmd[1],
"file_size": file_size,
}
print(header_dic)
json_str = json.dumps(header_dic)
json_str_bytes = json_str.encode('utf-8')
x = struct.pack('i', len(json_str_bytes))
print(x)
conn.send(x)
conn.send(json_str_bytes)
conn.send(file_data) except Exception:
break
conn.close()

最新文章

  1. Splash页面跳转主页面,去掉主页面标题栏
  2. C#设计模式-代理模式
  3. Kaggle入门教程
  4. js判断手机浏览器是横屏or竖屏
  5. JQuery学习(选择器-可见性-hidden)
  6. 无线局域网络 WIFI/WAPI/WLAN区别浅析
  7. digitalocean添加ssh_keys
  8. 为不同浏览器创建XMLHttpRequest对象
  9. js/jQuery实现复制到剪贴板功能,兼容所有浏览器
  10. TensorFlow文本与序列的深度模型
  11. Failed to retrieve procctx from ht. constr
  12. leetCode Min Stack解决共享
  13. First Article
  14. Makefile例子引入
  15. 10分钟了解JSON Web令牌(JWT)
  16. pyHook和pythoncom的安装
  17. python 环境下 安装 gdal
  18. css自动换行如何设置?url太长会撑开页面
  19. top结果解释
  20. python scrapy爬虫数据库去重方法

热门文章

  1. 我们为什么要用hibernate
  2. 简单5步,轻松debug K8S服务!
  3. php的ts和nts选择
  4. 【JAVA进阶架构师指南】之五:JVM性能调优
  5. cc32b_demo-32dk2j_cpp_纯虚函数与抽象类2-txwtech
  6. ABP (.Net Core 3.1版本) 使用MySQL数据库迁移启动模板项目(1)
  7. 登录CentOS用户很慢/usr/bin/xauth: timeout in locking authority file /home/***/.Xauthority
  8. CF #640 (div4)
  9. 从外包公司运作方式看EJB工作原理
  10. Java 多线程基础(十一)线程优先级和守护线程