On server: I am loading a png image:
var myimage = png.load('test.png');
then sending over websocket connection:
ws.send(myimage);
On client:
function onMessage(evt) {
if (evt.data instanceof ArrayBuffer) {
var length = evt.data.byteLength;
var bytes = new Uint8Array(evt.data);
var image = document.getElementById("image");
var img = new Image();
img.src = 'data:image/png;base64,'+ window.btoa(bytes);
var ctx = image.getContext("2d");
ctx.drawImage(img, 0, 0);
}
Not getting anything to display on canvas. Any ideas about what I'm doing incorrectly?
You can either combine websocket.py into your python server and use send_frames directly, or add framing to your 'protocol'. If the only thing you are sending in PNG images, you could parse the length out. Otherwise, you'll have to add your own framing from the python server.
The key word in that definition is two-way: with WebSocket, both the client and the server can trigger communication with one another, and both can send messages, at the same time.
Avoid using WebSockets if only a small number of messages will be sent or if the messaging is very infrequent. Unless the client must quickly receive or act upon updates, maintaining the open connection may be an unnecessary waste of resources.
Sending Messages With WebSocket You can send both text and binary data through a WebSocket. For your demo application you need to send the contents of the textarea to the server when the form is submitted. To do this you first need to set up an event listener on the form.
Try creating a blob and converting that to a blob url
function onMessage(evt) {
if (evt.data instanceof ArrayBuffer) {
var length = evt.data.byteLength;
var blob = new Blob([evt.data],{type:'image/png'});
var url = URL.createObjectURL(blob);
var image = document.getElementById("image");
var img = new Image();
img.onload = function(){
var ctx = image.getContext("2d");
ctx.drawImage(img, 0, 0);
}
img.src = url;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With