Python socket closed before all data have been consumed by remote

2024/5/20 13:19:37

I am writing a Python module which is communicating with a go program through unix sockets. The client (the python module) write data to the socket and the server consume them.

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

My issue is that the Python client tends to finish and close the socket before the data have been effectively read by the server which leads to a "broken pipe, connection reset by peer" on the server side. Whatever I do, for the Python code everything has been sent and so the calls to send() sendall() select() are all successful...

Thanks in advance

EDIT: I can't use shutdown because of mac OS

EDIT2: I also tried to remove the timeout and call setblocking(True) but it doesn't change anything

EDIT3: After ready this issue http://bugs.python.org/issue6774 it seems that the documentation is unnecessary scary so I restored the shutdown but I still have the same issue:

# 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()
Answer

IHMO this is best done with an Asynchornous I/O library/framework. Here's such a solution using circuits:

The server echos what it receives to stdout and the client opens a file and sends this to the server waiting for it to complete before closing the socket and terminating. This is done with a mixture of Async I/O and Coroutines.

server.py:

from circuits import Component
from circuits.net.sockets import UNIXServerclass Server(Component):def init(self, path):UNIXServer(path).register(self)def read(self, sock, data):print(data)Server("/tmp/server.sock").run()

client.py:

import sysfrom circuits import Component, Event
from circuits.net.sockets import UNIXClient
from circuits.net.events import connect, close, writeclass done(Event):"""done Event"""class sendfile(Event):"""sendfile Event"""class Client(Component):def init(self, path, filename, bufsize=8192):self.path = pathself.filename = filenameself.bufsize = bufsizeUNIXClient().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:breakfinally: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 noerrors and the servers gets the complete file before the client clsoesthe socket and shuts down.

https://en.xdnf.cn/q/72912.html

Related Q&A

Python child process silently crashes when issuing an HTTP request

Im running into an issue when combining multiprocessing, requests (or urllib2) and nltk. Here is a very simple code:>>> from multiprocessing import Process >>> import requests >>…

Shared variable in concurrent.futures.ProcessPoolExecutor() python

I want to use parallel to update global variable using module concurrent.futures in pythonIt turned out that using ThreadPoolExecutor can update my global variable but the CPU did not use all their pot…

MongoEngine - Another user is already authenticated to this database. You must logout first

Can anyone please explain why I am getting error Another user is already authenticated to this database. You must logout first when connecting to MongoDB using Flask MongoEngine?from mongoengine.conne…

How to bucketize a group of columns in pyspark?

I am trying to bucketize columns that contain the word "road" in a 5k dataset. And create a new dataframe. I am not sure how to do that, here is what I have tried far : from pyspark.ml.featur…

Dictionary of tags in declarative SQLAlchemy?

I am working on a quite large code base that has been implemented using sqlalchemy.ext.declarative, and I need to add a dict-like property to one of the classes. What I need is the same as in this ques…

How to connect to a GObject signal in python, without it keeping a reference to the connecter?

The problem is basically this, in pythons gobject and gtk bindings. Assume we have a class that binds to a signal when constructed:class ClipboardMonitor (object):def __init__(self):clip = gtk.clipboar…

openpyxl please do not assume text as a number when importing

There are numerous questions about how to stop Excel from interpreting text as a number, or how to output number formats with openpyxl, but I havent seen any solutions to this problem:I have an Excel s…

NLTK CoreNLPDependencyParser: Failed to establish connection

Im trying to use the Stanford Parser through NLTK, following the example here.I follow the first two lines of the example (with the necessary import)from nltk.parse.corenlp import CoreNLPDependencyPars…

How to convert hex string to color image in python?

im new in programming so i have some question about converting string to color image.i have one data , it consists of Hex String, like a fff2f3..... i want to convert this file to png like this.i can c…

How to add values to a new column in pandas dataframe?

I want to create a new named column in a Pandas dataframe, insert first value into it, and then add another values to the same column:Something like:import pandasdf = pandas.DataFrame() df[New column].…