python - 通过 Python 套接字发送 Zip 文件夹
问题描述
因此,由于某种原因,此代码无法正常工作,无法将 zip 文件夹从客户端发送到服务器。在服务器端,如果我使用 "f = zipfile.ZipFile("platformIO.zip")" 我收到错误 "ValueError: stat: embedded null character in path",如果我使用 "f = open("platformIO.zip" ", "wb")" 不会抛出错误,但接收到的文件已损坏且无法打开。
我已经阅读了所有与此类似的问题,但找不到解决方案。
客户:
import socket
import time
# Configure wireless connection with server (board on leg)
HOST = "192.168.4.1" # change to server ip address
PORT = 5005 # must be same as server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
print("connected")
user_input = "startup"
while True:
if user_input == "startup":
# ask if user wants to send code
user_input = input("Do you want to send new code?: (y/n)")
if user_input == "y":
user_input = "send code"
elif user_input == "n":
user_input = input("Would you like to collect data?: (y/n)")
if user_input == "y":
user_input = "receive data"
else:
user_input = "startup"
else:
user_input == "startup"
elif user_input == "send code":
st = "sending code"
s.send(st.encode())
file = "platformIO.zip"
try:
with open(file, "rb") as f:
print("sending file...")
data = f.read()
s.sendall(data)
print("finished sending")
st = "finished"
s.send(st.encode())
user_input = "startup"
except:
print("Failed transfering <platformIO.zip>, make sure it exists")
st = "failed"
s.send(st.encode())
elif input =="receive data":
print("feature not yet implemented")
user_input == "startup"
# delay
time.sleep(0.1)
服务器:
import socket
import time
import zipfile
import os
# create server
HOST = "192.168.4.1"
PORT = 5005
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("socket created")
# managing error exception
try:
s.bind((HOST,PORT))
except socket.error:
print("bind Failed")
s.listen(1)
print("Socket awaiting mesesages")
(conn, addr) = s.accept()
print("connected")
# awaiting message
msg = "startup"
while True:
if msg == "startup":
# receive data from controller
msg = conn.recv(4096)
print(str(msg, 'utf-8'))
elif str(msg, 'utf-8') == "sending code":
f = zipfile.ZipFile("platformIO.zip", "w")
#f = open("platformIO.zip", "wb")
while True:
data = conn.recv(4096)
print(data)
if not data:
break
f.write(data)
print("file received")
msg = "startup"
time.sleep(.1)
conn.close()
编辑:如果我使用 f = open("platformIO.zip", "wb") 并在服务器的写入 while 循环中添加 s.close() ,我可以成功接收 zip,但随后连接关闭,我可以'在我关闭程序之前不要打开 zip 文件
f = open("platformIO.zip", "wb")
while True:
data = conn.recv(4096)
print(data)
if not data:
break
f.write(data)
s.close()
解决方案
推荐阅读
- module - 如何在 azure terraform 中访问模块 [NIC] 输出到另一个模块 [VM] 的元组值类型列表
- react-native - 当应用程序处于后台或终止状态时,抬头或通知横幅不会从顶部弹出|| 反应原生火力基地 || fcm
- javascript - TranslateService 无法翻译日期字符串不正确
- linux - I want to move whole mongo databse to linux
- jsp - 为什么Tomcat在导入普通对象时会出错?
- javascript - 如何使用默认导出保留“实时绑定”
- c - 如何从C中的函数获取字符串作为返回值?
- swift - 参数类型(字符串)->()的问题-SwiftUI
- android - android 应用程序中活动和多片段的单视图模型
- r - 因子水平无效,仅针对因子变量中的一个水平生成 NA