gpt4 book ai didi

Python 套接字在远程使用所有数据之前关闭

转载 作者:太空狗 更新时间:2023-10-30 00:19:26 26 4
gpt4 key购买 nike

我正在编写一个 Python 模块,它通过 unix 套接字与 go 程序通信。客户端(python 模块)将数据写入套接字,服务器使用它们。

# Simplified version of the code used
outputStream = socket.socket(socketfamily, sockettype, protocol)
outputStream.connect(socketaddress)
outputStream.setblocking(True)
outputStream.sendall(message)
....
outputStream.close()

我的问题是 Python 客户端倾向于在数据被服务器有效读取之前完成并关闭套接字,这导致服务器端出现“管道损坏,连接被对等方重置”。无论我做什么,对于 Python 代码,所有内容都已发送,因此对 send() sendall() select() 的调用都是成功的...

提前致谢

编辑:由于 mac OS,我无法使用关机

EDIT2:我也尝试删除超时并调用 setblocking(True) 但它没有改变任何东西

EDIT3:准备好这个问题后http://bugs.python.org/issue6774似乎文档是不必要的可怕所以我恢复了关机但我仍然有同样的问题:

# Simplified version of the code used
outputStream = socket.socket(socketfamily, sockettype, protocol)
outputStream.connect(socketaddress)
outputStream.settimeout(5)
outputStream.sendall(message)
....
outputStream.shutdown(socket.SHUT_WR)
outputStream.close()

最佳答案

IHMO 这最好使用异步 I/O 库/框架来完成。这是使用 circuits 的解决方案:

服务器将接收到的内容回显到标准输出,客户端打开一个文件并将其发送到服务器等待它完成,然后关闭套接字并终止。这是通过混合使用异步 I/O 和协同程序完成的。

server.py:

from circuits import Component
from circuits.net.sockets import UNIXServer

class Server(Component):

def init(self, path):
UNIXServer(path).register(self)

def read(self, sock, data):
print(data)

Server("/tmp/server.sock").run()

客户端.py:

import sys

from circuits import Component, Event
from circuits.net.sockets import UNIXClient
from circuits.net.events import connect, close, write

class done(Event):
"""done Event"""

class sendfile(Event):
"""sendfile Event"""

class Client(Component):

def init(self, path, filename, bufsize=8192):
self.path = path
self.filename = filename
self.bufsize = bufsize

UNIXClient().register(self)

def ready(self, *args):
self.fire(connect(self.path))

def connected(self, *args):
self.fire(sendfile(self.filename, bufsize=self.bufsize))

def done(self):
raise SystemExit(0)

def sendfile(self, filename, bufsize=8192):
with open(filename, "r") as f:
while True:
try:
yield self.call(write(f.read(bufsize)))
except EOFError:
break
finally:
self.fire(close())
self.fire(done())

Client(*sys.argv[1:]).run()

In my testing of this it behaves exactly as I expect it to with no errors and the servers gets the complete file before the client clsoes the socket and shuts down.

关于Python 套接字在远程使用所有数据之前关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30620681/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com