1

I am using python SimpleWebSocketServer, with a modified SimpleExample.py and Chrome.

Everything works fine when I send strings from browser to python, but when I send string from python to browser, I don't have the faintest idea how to transform the received ArrayBuffer (or Blob, if configured so) into a javascript string.

Python code:

def handleConnected(self):
    with open("roads.txt") as roadsfile:
        content = "" + roadsfile.read()
        self.sendMessage(content)

Browser code:

    function doConnect() {
        websocket = new WebSocket("ws://localhost:8000/");
        websocket.binaryType = 'arraybuffer';
        websocket.onmessage = function(event) { onMessage(event) };
    }

    function onMessage(event) {
        console.log(event.data);
    }

And what's get logged is just ArrayBuffer{}, appearing to be empty, I guess.

I don't know what to do with this ArrayBuffer, neither how to check for its validity.

By the way, the file content from roads.txt is one long line of text-based floats, similar to .csv, so if I could encode them as an actual binary array, the better!

heltonbiker
  • 26,657
  • 28
  • 137
  • 252
  • This might help: https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String?hl=en – ErikR Jun 01 '16 at 03:10
  • maybe leave off `websocket.binaryType = 'arraybuffer';` and see if you can get a regular string. – domoarigato Jun 01 '16 at 03:13
  • @domoarrigato, now I get `Blob {size: 70127, type: ""}` on `console.log` – heltonbiker Jun 01 '16 at 03:21
  • @heltonbiker: can you please help me with https://stackoverflow.com/questions/44939566/angularjs-how-to-send-files-via-websocket. also, please provide the solution which u applied for receiving it via ws – Samuel Jul 06 '17 at 18:48

1 Answers1

0

Try this - go back to receiving the message as an arraybuffer, and apply something like this to make a string:

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}

function onMessage(event) {
    console.log(ab2str(event.data));
}

this assumes you are sending a utf-8 encoded string.

domoarigato
  • 2,802
  • 4
  • 24
  • 41