9

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.

Cris
  • 12,799
  • 5
  • 35
  • 50
user33054
  • 91
  • 1
  • 1
  • 3
  • can you do a basic one? http://www.tutorialspoint.com/html5/html5_websocket.htm like on that page? –  Jul 06 '13 at 14:31

3 Answers3

8

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

Terry
  • 533
  • 7
  • 17
2

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 = function(evt) { responseData(evt); };
function responseData(evt) {
    /* Here is your data, Do you what you want! */
    console.log(JSON.parse(evt.data));
}
0

Once you created an instance of your websocket using new , will be able to get message event OnMessage . If you using react then ,

    useEffect(() => {
    WebSocketScale.onmessage = (event: any) => {
        value.push(JSON.parse(event.data));
}, []);