Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Websocket wait for connection and readystate change before sending message

I am using Websockets in my React app, and I have to connect to a web socket and then sent a message as soon as it gets connected. but my code do not works in sync

Here it is

ws = new WebSocket(uri);
ws.send('my msg');

Is there a way to wait for connection established and ready state changed! Thanks!

like image 962
h_h Avatar asked Oct 28 '25 22:10

h_h


1 Answers

From the docs on MDN:

// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');

// Connection opened
socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});
like image 134
user3297291 Avatar answered Oct 31 '25 15:10

user3297291



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!