javascript websocket onmessage event.data

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15514155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:02:34  来源:igfitidea点击:

javascript websocket onmessage event.data

javascriptwebsocket

提问by user33054

Using JavaScript WebSocket how to pass event.dataout onMessagefunction?

使用JavaScript的WebSocket怎么传event.data出来onMessage的功能?

var eventData = EventRequest("text");


  ..... codes .....


EventRequest = function (text)
{
   var socket = new WebSocket ('ws://localhost:8080/');
   websocket.onopen = function(evt) { onOpen(evt); };
   websocket.onmessage = function(evt) { onMessage(evt); };

function onOpen (evt)
{
   socket.send("text");
}

function onMessage (evt)
{
   alert (evt.data);
   return evt.data;
}
};

I tried different ways to pass evt.data out, but I have not been able to. I can see the correct evt.datadata. I just can not pass the data out of onMessagefunction.

我尝试了不同的方法来传递 evt.data,但我一直没能做到。我可以看到正确的evt.data数据。我只是无法将数据传递出去onMessage

I tried

我试过

function wcConnection (){
   this.dataInput = '';
}

Inside onMessagefunction, I added

onMessage函数内部,我添加了

function onMessage (evt)
{
   alert (evt.data);
   this.dataInput = evt.data;
}

Any help would be appreciated.

任何帮助,将不胜感激。

回答by Terry

If you server is python tornado

如果你的服务器是 python 龙卷风

def on_message(self, message):
        t = json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
        self.write_message(t)

In your client, to retrieve the message, you could do

在您的客户端中,要检索消息,您可以执行以下操作

ws.onmessage = function (evt) { 
    console.log(JSON.parse(event.data));
}

you should see the json in the console

您应该会在控制台中看到 json

回答by Mohit Satish Pawar

Why are you returning value to websocket.onmessage function? This is the function where you got that value. If you want to pass the value to another function just pass the event object to that function and access it using "evt.data".

为什么要向 websocket.onmessage 函数返回值?这是您获得该值的函数。如果您想将值传递给另一个函数,只需将事件对象传递给该函数并使用“evt.data”访问它。

websocket.onmessage = function(evt) { responseData(evt); };
function responseData(evt) {
    /* Here is your data, Do you what you want! */
    console.log(JSON.parse(evt.data));
}