I'm just starting learning websockets, andI get a strange error:
<script type="text/javascript">
window.onload = function(){
var service = new WebSocket("ws://localhost:8080/websocket/test");
service.onmessage = function(event){
alert("message");
}
service.onopen = function(){
service.send("hello!");
}
service.onclose = function(){
alert("closed");
}
service.onerror = function(){
alert("error");
}
service.send("test");
service.close();
}
</script>
on the line:
service.send("test");
I get:
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
Am I missing something important?
Solution 1Check that all the Bot Insight services are running. Check that your firewall settings are configured to accept incoming websocket data. Try to use a different web browser. Restart the Bot Insight Visualization and Bot Insight Scheduler services.
Data Types and ExtensionsWebSockets support sending binary messages, too. To send binary data, one can use either Blob or ArrayBuffer object. Instead of calling the send method with string, you can simply pass an ArrayBuffer or a Blob .
The WebSocket. send() method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of bufferedAmount by the number of bytes needed to contain the data.
Unlike the HTTPS protocol, WebSocket allows for data transfer in both directions. WebSockets can be used to build out anything from a real-time trading application to a chat application, or just about anything that requires efficient, real-time data transfer.
The WebSocket.onopen property is an EventHandler that is called when the WebSocket connection's readyState changes to OPEN; this indicates that the connection is ready to send and receive data.
Once you've opened your connection, you can begin transmitting data to the server.
window.onload = function() {
var service = new WebSocket("wss://echo.websocket.org");
service.onmessage = function(event) {
alert("onmessage event: "+event.data);
}
service.onopen = function() {
service.send("test"); //Will work here!
//^^^^^^^^^^^^^^^^^
service.send("hello!");
}
service.onclose = function() {
alert("closed");
}
service.onerror = function() {
alert("error");
}
//Can't close while a connection is still being established.
//service.close();
}
If you use Websocket().send() outside your service.onopen(), you can still check the readyStatebefore sending message, like this:
websocket.sendmessage = async function(msg) {
while (this.readyState === 0) {
await sleep(200);
}
this.send(msg);
};
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