python - 使用 Python Socket 分块发送和接收文件
问题描述
我正在尝试通过 Python 3.9 套接字发送和接收文件,但我的代码只工作了一半。
客户端(文件阅读器)的代码:
import socket
r = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
r.connect((socket.gethostname(), 8080))
with open("fileToRead.jpg", "rb") as fileReader:
for data in fileReader:
r.send(data)
r.send("flag".encode())
print("I have finished reading")
userInp = ""
while userInp != "exit":
userInp = input("Enter input: ")
r.close()
服务器的代码(文件编写器):
import socket
w = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
w.bind((socket.gethostname(), 8080))
w.listen(1)
conn, addr = w.accept()
print("Connection made from ", addr)
with open("fileToWrite.jpg", "wb") as fileWriter:
while True:
data = conn.recv(1024)
if data.decode() == "flag":
break
fileWriter.write(data)
print("just wrote data")
print("I have finished writing")
while True:
input("Test to see if I can work after file transfer: ")
传输文件后,我需要客户端和服务器仍然保持连接。我提供的代码只为我工作了一半,我不知道为什么。一半不工作,服务器卡在行print("just write data")
解决方案
推荐阅读
- html - 如何使导航栏的文本居中
- c# - Asp.net core 3.1 mvc post request model binding for simple types
- python - 设置虚拟环境时,windows 和 linux 的 sys.path 的值不同
- haskell - `readIORef` 怎么会是阻塞操作
- makefile - Makefile - 根据目标生成不同的相同文件
- bash - 管道包版本号并从版本号创建一个 git 标签
- javascript - 有人能解释一下像“for (;;)”这样的循环的语法吗
- bitbucket - 如何在 Bitbucket JIRA pre hook 中匹配 jql 的任何问题
- azure-machine-learning-service - 先前实验中的最佳运行和模型代码
- reactjs - React 形式的 Java 方法