Reputation: 454
I have been trying to use socketio to stream files from nodejs server to the python socketio client. However I don't have a proper idea how to stream image. Currently I am just using readFile
in Nodejs. This is what I have written so far to read the file and send it as an whole:
var socket = req.app.get('socket');
readFile(req.file.path, 'utf-8', (err, data) => {
socket.emit('image', { buffer: data, metadata: req.file }, (response) => {
console.log(response);
});
});
On python socketio client's side, I want to save the file to a folder assets
and I have written this code:
@sio.event
async def image(data):
try:
filehandler = open('assets/' + data['metadata']['filename'] + '.jpeg', 'w')
filehandler.write(data['buffer'])
filehandler.close()
except:
return 'NOT OK'
finally:
return 'OK'
However, the final file written is not readable as an image and I am not able to open it. Please correct my code as required for this to work properly.
Moreover, I want to stream the file from Nodejs instead of reading it whole and then sending it.
I would really appreciate it if I got code for both methods but at least need the code for streaming the file.
Thanks!!
Upvotes: 1
Views: 970
Reputation: 98
I was able to solve this issue for readFile. I removed the 'utf-8'
argument from Nodejs and this is the updated code:
readFile(req.file.path, (err, data) => {
// I used multer so req.file has the file's metadata but doesn't contain buffer
socket.emit('image', { buffer: data, metadata: req.file }, (response) => {
console.log(response);
});
});
On python socketio client's end, I used pillow:
@sio.on('image')
async def tryon(data):
image = Image.open(io.BytesIO(data['buffer']))
image.show()
image.save('assets/' + data['metadata']['filename'] + '.png')
# I tried to write the above code into opencv but was facing errors.
# Skipping it for now. You can refer it if you are willing to further debug it.
# img = cv2.imread(np.frombuffer(data['buffer']))
# cv2.imwrite('assets/' + data['metadata']['filename'] + '.jpeg', img)
return 'OK'
Upvotes: 1
Reputation: 1481
Your question is answered in the usage example of socket.io-stream
.
edit: However on the Python side, there seems to be no support:
The Socket.IO protocol doesn't have anything called "streaming". I think you are looking at an extension built by a 3rd party that works on top of the standard Socket.IO packet exchange mechanisms.
Upvotes: 1