Reputation: 149
I'm trying to send an image with WebSocket but it won't work.
As I send plain text or json it works like a charm, but not with an image. It seems Flask can't map the request with files.
In addition, it works just fine in reverse. The image from server, which encoded with cv2 was sent and received successfully.
Client (Sender)
socket.on('socket_respond', (result) => {
const blob = new Blob([result])
const url = URL.createObjectURL(blob, 'image/png');
const image = document.createElement('img');
image.className = 'result';
image.src = url;
app.append(image);
});
async function handleSubmit (event) {
event.preventDefault();
if (!file.value.length)
return;
let reader = new FileReader();
reader.onload = (event) => {
# I have tried the method with reader.readAsDataURL and reader.readAsArrayBuffer as well.
};
reader.readAsDataURL(file.files[0]);
# This does work. plain text (string)
socket.emit('socket_request', 'test');
# This does work. json
socket.emit('socket_request', { test: 'test' });
# This does not work.
socket.emit('socket_request', files.files[0]);
}
Server (Receiver)
@socket_io.on('socket_request')
def foo(arg):
print(arg)
image = cv2.imencode('.png', cv2.imread(f'{INPUT_PATH}/images/pic.png'))[1].tobytes()
emit('socket_respond', image, broadcast=False)
Upvotes: 0
Views: 224
Reputation: 149
It was problem with server-side, notice that from flask to client was worked. That's because the client-side has no size limit of socket request. But server has size limit of 1 MB, so with large iamge file the request was ignored.
All I had to do was is follwing.
socket_io = SocketIO(app, max_http_buffer_size=10000000)
Create socket_io with desired max_http_buffer_size argument.
Upvotes: 0