2016-06-01 54 views
1

我使用python SimpleWebSocketServer,修改了SimpleExample.py和Chrome。我发送字符串从Python到浏览器,我没有最隐秘的想法如何将接收到的ArrayBuffer(或Blob,如果配置如此)转换为javascript字符串。通过websocket从ArrayBuffer接收字符串

Python代码:

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

浏览器代码:

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

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

,什么是得到记录只是ArrayBuffer{},看来是空的,我猜。

我不知道如何处理这个ArrayBuffer做,既不是如何检查的有效性。

顺便说一句,来自roads.txt的文件内容是基于文本的浮动的一个很长的行,类似于.csv,所以如果我可以将它们编码为实际的二进制数组,则更好!

+0

这可能有所帮助:https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String?hl = zh_CN – ErikR

+0

可能会忽略'websocket .binaryType ='arraybuffer';'看看你是否可以得到一个普通的字符串。 – domoarrigato

+0

@domoarrigato,现在我在'console.log'上得到'Blob {size:70127,type:“”}'' – heltonbiker

回答

0

试试这个 - 回去接收消息作为arraybuffer,并应用这样的事情做一个字符串:

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

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

这个假定您发送的是UTF-8编码的字符串。

+0

申请接收它的解决方案我试过了,但现在控制台日志是空的(空白)。 – heltonbiker