I have the following html/javascript code that uses websockets to communicate with a server. It seems like I can only send(message) only inside the onmessage() and onopen() functions. How can I send data outside of those functions ?
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
var ws = new WebSocket("ws://localhost:57252/");
ws.onopen = function () {
ws.send("Hi, from the client."); // this works
alert("Connection opened...");
};
ws.onmessage = function (event) {
alert("Message received..." + event.data);
};
ws.onclose = function () {
alert("Connection closed...");
};
ws.send("Hi, from the client."); // doesn't work
ws.send("Hi, from the client."); // doesn't work
}
}
</script>
</head>
<body>
<div id="sse">
Run WebSocket
</div>
</body>
</html>
You are probably experiencing a race condition where you try to perform a send command even though the socket may not have been opened yet. There's an important note on the MDN that describes this behavior:
As establishing a connection is asynchronous and prone to failure there is no guarantee that calling the send() method immediately after creating a WebSocket object will be successful.
You, essentially, are calling the send method immediately after creating a WebSocket.
If you move that logic to a function and call that function when you know the connection has been open, you might be fine. For example, try moving the code into a timeout or another function that can be manually triggered after you know the socket connection has been established:
function sendMyMessages() {
ws.send("Hi, from the client.");
ws.send("Hi, from the client.");
}
<button onclick="sendMyMessages()">Test</button>
Because onopen is an asynchronous event.
It's similar to doing this:
var value;
$.ajax({
url: '/post/data',
success: function(response) {
value = response;
}
});
alert(value);
What do we get in the alert? undefined.
The websocket works in a similar manner, you cannot send until the connection has finished opening. It opens asynchronously. Therefore, anytime you try to use send, you must ensure that the connection is already open. Right now, you are trying to synchronously use those send calls, before the connection is actually open.
This is the html file of Sanic webserver websocket demo.
<!DOCTYPE html>
<html>
<head>
<title>WebSocket demo</title>
</head>
<body>
<script>
var ws = new WebSocket('ws://' + document.domain + ':' + location.port + '/feed'),
messages = document.createElement('ul');
ws.onmessage = function (event) {
var messages = document.getElementsByTagName('ul')[0],
message = document.createElement('li'),
content = document.createTextNode('Received: ' + event.data);
message.appendChild(content);
messages.appendChild(message);
};
document.body.appendChild(messages);
window.setInterval(function() {
data = 'bye!'
ws.send(data);
var messages = document.getElementsByTagName('ul')[0],
message = document.createElement('li'),
content = document.createTextNode('Sent: ' + data);
message.appendChild(content);
messages.appendChild(message);
}, 1000);
</script>
</body>
Related
I am integration a desktop application with my asp.net mvc app. Desktop application is publishing the data on port:10000 which i need to listen in browser. Below is the code:
<html>
<head>
<script type = "text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://127.0.0.1:10000");
ws.onopen = function() {
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function() {
// websocket is closed.
alert("Connection is closed...");
};
} else {
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id = "sse">
Run WebSocket
</div>
</body>
</html>
The issue I am facing is when desktop app publish the data on port, connection terminates and i am getting a message connection closed. any help?
Looking at your code i dont see anywhere where you close the conecction with ws, so i think its the server who closes the connection after sending you the message.
I have arduino esp32 which i have sent data over mqtt to my cloudmqtt broker.
What it is sending is real time random numbers.
I can view these numbers on the cloudmqtt broker but i want it to be transferred to my webpage, so i researched and found some information on websockets.
This is the code i have currently:
<html>
<head>
<title>JavaScript MQTT WebSocket Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
var mqtt;
var reconnectTimeout = 2000;
var host = "farmer.cloudmqtt.com"; //change this
var port = 37511;
var user = "foo";
var pass = "bar";
function MQTTconnect() {
console.log("connecting to " + host + " " + port);
mqtt = new Paho.MQTT.Client("farmer.cloudmqtt.com", 37511, "web_" + parseInt(Math.random() * 100, 10));
mqtt.onMessageArrived = onMessageArrived;
//document.write("connecting to "+ host);
var options = {
useSSL: true,
userName: "foo",
password: "bar",
onSuccess: onConnect,
onFailure: doFail
};
mqtt.connect(options); //connect
};
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("Connected ");
//mqtt.subscribe("sensor1");
message = new Paho.MQTT.Message("Hello world");
message.destinationName = "esp/test";
mqtt.send(message);
}
function doFail(e) {
console.log(e);
}
function onMessageArrived(message) {
console.log("onMessageArrived:" + message.payloadString);
}
</script>
</head>
<body>
<h1>Main Body</h1>
<script>
MQTTconnect();
</script>
</body>
</html>
But when i view my conosle it doesnt seem to work and gives error:
HTML1300: Navigation occurred.
webpage.html (1,1)
HTML1527: DOCTYPE expected. Consider adding a valid HTML5 doctype: “”.
webpage.html (1,1)
connecting to farmer.cloudmqtt.com 37511
webpage.html (14,13)
0: Unspecified error.
mqttws31.min.js (28,16)
I am not sure why i get this error i dont see any errors in my code.
I'm trying to configure a WebSocket in Scala. I have a function that broadcasts a bunch of JSON to a WebSocket. It works when I configure it through http://www.websocket.org/echo.html (inputting my own ws://localhost:9000/web-socket), but I need it to display the information on a new webpage.
To that effect I made a new webpage called client which is defined in my controllers as
def client = Action {
val data = new RedshiftData() // get the data
Ok(views.html.client(data))
}
In my views I have client.scala.html defined as (adapted from websockets.org)
#import datadump.RedshiftData
#(data: RedshiftData)
<!DOCTYPE html>
<html>
<script>
var wsUri = "ws://localhost:9000/web-socket";
var ws = new WebSocket(wsUri);
#data.pushToWebSocket
ws.onmessage = function (evt) {
var msg = JSON.parse(evt.data);
console.log(msg);
};
</script>
<body>
</body>
</html>
But, it never receives my message that I'm sending. How do I get it to listen to the message that I send out in the controller?
This question has already been answered, but I can't understand it at all. You can find it at this link.
socket.on calls its callback too many times
I have the same problem as this fellow. I'm attempting to make a chat program with socket.io, but when more than one user joins, each message outputs the number of times of how many users have been connected.
For example, when one user is connected, and he submits a message. It outputs once. When two users are connected, each of their messages output twice.
When three users are connected, each of their messages output three times.
Here is my client side code:
$('document').ready(function() {
var server = io.connect('http://localhost:8888');
$('.chat').keydown(function(event){
var save = this;
if(event.which == 13){
server.emit('message', $(save).val());
$(save).val('');
return false;
}
});
server.on('incoming', function(message){
$('#textfield').append("<p>" + message + "</p>");
});
});
Here is my server side code:
var socket_io = require('socket.io').listen(8888).sockets;
socket_io.on('connection', function(socket){
socket.on('message', function(message){
socket_io.emit('incoming', message)
});
});
Thank you!
You can use socket.broadcast.emit() to send to everyone except that socket:
var io = require('socket.io')(8888);
io.on('connection', function(socket) {
socket.on('message', function(message) {
socket.broadcast.emit('incoming', message);
});
});
UPDATE: The following example works just fine for me:
server.js:
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function(socket) {
socket.on('message', function(message) {
socket.broadcast.emit('incoming', message);
});
});
index.html:
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
$('document').ready(function() {
var server = io.connect('http://localhost');
$('.chat').keydown(function(event) {
if (event.which == 13) {
var $save = $(this);
server.emit('message', $save.val());
$save.val('');
return false;
}
});
server.on('incoming', function(message){
$('#textfield').append("<p>" + message + "</p>");
});
});
</script>
</head>
<body>
<input type="text" class="chat">
<div id="textfield"></div>
</body>
</html>
When pressing enter, the message in the input box is only displayed once to all other connected socket.io users.
Okay, I've finally figured out the problem.
I'm using Express 4.0. That means, I'm using routes to run the server, and I had the socket io code running inside the route. Each time a user connects, it has to go through the route first, and it's all binding onto the same socket_io.
Thanks to everybody who helped!
I also faced it, like multiple socket calls in network tab and i just add this "transports" key object to socket instance, both on client and backend.
socket = io("http://localhost:3002", {
transports: ['websocket']
})
React, Node, AWS EB
I'm using QWebSocketServer to provide communication with javascript websocket.
The code is very similar with EchoServer in Qt Examples.
javascript side code is listed as following:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window)
{
//alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:12345");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};
ws.onerror = function(error){
console.log('Error detected: ' + JSON.stringify(error));
}
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id="sse">
Run WebSocket
</div>
</body>
</html>
However, I get this error:
Error detected: {"path":{"length":0},"cancelBubble":false,"returnValue":true,"srcElement":{"binaryType":"blob","extensions":"","protocol":"","bufferedAmount":0,"readyState":3,"url":"ws://localhost:12345/","URL":"ws://localhost:12345/"},"defaultPrevented":false,"timeStamp":1408698611478,"cancelable":false,"bubbles":false,"eventPhase":2,"currentTarget":{"binaryType":"blob","extensions":"","protocol":"","bufferedAmount":0,"readyState":3,"url":"ws://localhost:12345/","URL":"ws://localhost:12345/"},"target":{"binaryType":"blob","extensions":"","protocol":"","bufferedAmount":0,"readyState":3,"url":"ws://localhost:12345/","URL":"ws://localhost:12345/"},"type":"error"}
What does this error mean? And does it mean that we cannot use QWebSocketServer to support javascript websocket?