javascript websocket connect to QWebSocketServer failed - javascript

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?

Related

How html to get dynamic src from java files?

I am planning to use the camera to capture images stream and make it can be shown in the web, just like a live stream. I have done the client part and the server part can receive the base64 data of each captured image. Below is the server code and the message represents the base64 data. My question is that how can I transfer the "message" to html file so that it can be used as src to locate the images? THX.
let WebSocketServer = require('ws').Server,
wss = new WebSocketServer({ port: 3303 });
wss.on('connection', function (ws) {
console.log('client is connected');
ws.on('message', function (message) {
wss.clients.forEach(function each(client) {
client.send(message);
});
console.log(message);
});
})
Below is the code of html file. What should I use to fill the "src" part?
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<img id="resImg" src = ""> </img>
</div>
<script src="jquery.min.js" ></script>
<script>
let ws = new WebSocket("ws://127.0.0.1:3303/");
ws.onopen = function(evt) {
console.log("Connection open ...");
ws.send("Hello WebSockets!");
};
ws.onmessage = function(evt) {
$("#resImg").attr("src",evt.data);
console.log( "Received Message: " + evt.data);
// ws.close();
};
ws.onclose = function(evt) {
console.log("Connection closed.");
};
</script>
</body>
</html>

HTML5 Websocket TCP Port Listening

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.

Error in my code trying get data from mqtt server to my web page Javascript

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 cannot send a message from my client using websocket to local server

I'm working on webstorm exactly a PhoneGap project and websocket and I cannot send a message from my client using websocket to local server. Thank you for your help.
<!--
Lincense: Public Domain
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample of web_socket.js</title>
<script src="js/websocket.js"></script>
<!-- Include these three JS files: -->
<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:9777");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("message");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
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>
I have been working on this problem for 2 days any help please!

Sending messages with Websockets

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>

Categories