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.
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 .
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With