Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript websocket onmessage event.data

Using JavaScript WebSocket how to pass event.data out onMessage function?

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.data data. I just can not pass the data out of onMessage function.

I tried

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

Inside onMessage function, I added

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

Any help would be appreciated.

like image 781
user33054 Avatar asked Mar 20 '13 02:03

user33054


People also ask

What is Onmessage WebSocket?

The WebSocket. onmessage property is an event handler that is called when a message is received from the server. It is called with a MessageEvent .

How do I get WebSocket data?

The Message event takes place usually when the server sends some data. Messages sent by the server to the client can include plain text messages, binary data, or images. Whenever data is sent, the onmessage function is fired.

How do you send data to a WebSocket?

To send a message through the WebSocket connection you call the send() method on your WebSocket instance; passing in the data you want to transfer. socket. send(data); You can send both text and binary data through a WebSocket.

Can WebSocket send binary data?

WebSocket enables bidirectional, message-oriented streaming of text and binary data between client and server. It is the closest API to a raw network socket in the browser.


1 Answers

If you server is python tornado

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

like image 100
Terry Avatar answered Nov 09 '22 08:11

Terry