I have an issue with a websocket client.
It seems to work fine in IE and Edge. The server responds with a message and the client receives and displays this message, but when my android device runs this code, the error handler gets fired off and the connection is closed immediately.
The error handler gives me a message: "undefined"
Here is my Client:
<!DOCTYPE html>
<html>
<head>
<title>HTML5 Touch Tracing </title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script type='text/javascript'>
function openSocket(){
if ("WebSocket" in window)
{
alert("WebSocket is supported by your Browser!");
//var WebSocket = require('ws');
var ws = new WebSocket("ws://localhost:8080/WebSocketServer/control");
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 = " + received_msg);
};
ws.onclose = function ()
{
// websocket is closed.
alert("Connection is closed...");
};
ws.onerror = function(evt)
{
alert("Error: " + evt.data);
};
} else
{
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<meta name="viewport" content="width=device-width,user-scalable=no">
<div>
Keyboard
</div>
</body>
</html>
My Server simply just responds with a message:
#OnMessage
public String onMessage(String message) {
return "Got it.";
}
Related
I am python developer but i need to see my websocket output from browser.
function startSocket() {
var ws = new WebSocket("ws://localhost:8765/")
ws.onopen = function(event) {
ws.send("Sent this from client.js")
console.log(typeof ws.message);
console.log("test")
console.log(ws.message)
}
}
startSocket();
this is my clien.js file.
<!DOCTYPE html><html lang="en">
<head>
<!-- <link rel="stylesheet" type="text/css" href="style.css">-->
<link type="text/css" href="styles.css">
<meta charset="utf-8">
</head>
<body>
<script src="client.js"></script>
</body></html>
and this is my html file.
I am sending a string from my web socket and i want to see inside of a browser.
When i run this html, my web socket is starting to work but my logs are saying undefined.
This is my Log Output
client.js:6 undefined
client.js:7 test
client.js:8 undefined
read more here
bind to the correct event handlers
function startSocket() {
var ws = new WebSocket("ws://localhost:8765/");
ws.onopen = function(event) {
console.log("connection opened");
ws.send("Sent this from client.js")
};
ws.onmessage = function(message) {
console.log(typeof message);
console.log("test")
console.log(message)
};
};
startSocket();
File in Desktop Image : index.html
Error Message Image : WebSocket connection to 'wss://graphigostream.prd.dlive.tv/' failed:
connect # index.html:9
File Path : file:///C:/Users/.../Desktop/index.html
Code:
<!doctype html>
<html>
<head>
</head>
<script>
function connect() {
var ws = new WebSocket('wss://graphigostream.prd.dlive.tv/', "graphql-ws");
ws.onopen = function() {
// ...
};
ws.onmessage = function(e) {
// ...
}
ws.onclose = function(e) {
// ...
};
ws.onerror = function(err) {
// ...
};
}
connect()
</script>
<body>
</body>
</html>
I want run this WebSocket through an HTML file, this url works in Nodejs, another website has the same and it works, I checked "window.WebSocket"
I am trying to set up a basic WSS websockets server. This is my minimal HTML (with the embedded javascript):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body style="background-color:white">
<h1>Test of WSS server</h1>
<p>Status: <span id=status"></span></p>
Click to send message
<script src="/newjs/jquery-2.1.1.js"></script>
<script>
var connection;
$(document).ready(function () {
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket) {
alert("browser says no");
console.log("Browser does not supports websockets");
return;
}
setupConnection();
});
function message() {
var msg = "Test Message";
connection.send(msg);
}
function setupConnection() {
connection = new WebSocket('wss://www.example.com:14000');
connection.onerror = function(error) {
console.log('onerror fired');
};
connection.onopen = function(event) {
$("#status").html("Open");
};
connection.onmessage = function (message) {
alert(message.data);
};
}
setInterval(function() {
if (connection.readyState !== 1) {
setupConnection();
}
}, 5000);
</script>
</body>
</html>
The following is the JS server run by nodejs:
var fs=require("fs");
var ws_cfg = {
ssl: true,
port: 14000,
ssl_key: '/httpd/conf/ssl.key/my.key',
ssl_cert: '/httpd/conf/ssl.crt/my.crt',
ca_cert: '/httpd/conf/ssl.crt/gd_bundle-g2-g1.crt'
};
var processRequest = function(req, res) {
console.log("Request received.")
};
var httpServ = require('https');
var app = null;
app = httpServ.createServer({
key: fs.readFileSync(ws_cfg.ssl_key),
cert: fs.readFileSync(ws_cfg.ssl_cert),
ca: fs.readFileSync(ws_cfg.ca_cert),
},processRequest).listen(ws_cfg.port);
var WebSocketServer = require('ws').Server, ws_server = new WebSocketServer( {server: app});
ws_server.on('open',function(request) {
console.log("opening");
});
ws_server.on('request', function(request) {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
if (request.origin!='https://www.example.com') {
console.log("rejecting request from " + request.origin + " as not coming from our web site");
return;
}
var connection = request.accept(null, request.origin);
connection.on('message', function(message) {
console.log("Got a message");
});
});
I fire up the server with node then load the web page in my browser (using either FF or Chrome). Using the developer tools I see that the connection appears to be made. On the server side I see the established connection using netstat. I also put an alert() in the browser side in the onopen() function and it fired.
The problem is that no console log output is produced. When connection.send(mag) is executed the on("message" event never appears to fire on the server. I'm at a loss here. I had this working as an http:// websocket server but this is my first attempt at wss:. I would appreciate any insight.
Notes:
The sever name is not example.com although that is what I show in my code.
The firewall is allowing anyone to connect on port 14000 using TCP protocol.
The cert is a working wildcard cert for the web site.
Finally figured out what it was after ignoring it for a month or so. It had to do with the symbolic link (/httpd) defined for the SSL files as in:
ssl_key: '/httpd/conf/ssl.key/my.key',
ssl_cert: '/httpd/conf/ssl.crt/my.crt',
They had to be changed to:
ssl_key: '/usr/local/apache2/conf/ssl.key/my.key',
ssl_cert: '/usr/local/apache2/conf/ssl.crt/my.crt',
Who knew that symbolic links were frowned upon? Well, now we all do.
I was trying to develop a simple web application using the MQTT Broker. I used Mosca as the broker on localhost. First I tried out a program copied from the web to see how MQTT works. This is the program.
home.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="mqttws31.js" type="text/javascript"></script>
<script src="client.js">
</script>
</head>
<body onload="init();">
</body>
</html>
client.js
var wsbroker = "127.0.0.1"; //mqtt websocket enabled broker
var wsport = 3000 // port for above
var client = new Paho.MQTT.Client(wsbroker, wsport,
"myclientid_" + parseInt(Math.random() * 100, 10));
client.onConnectionLost = function (responseObject) {
alert("connection lost: " + responseObject.errorMessage);
};
client.onMessageArrived = function (message) {
alert(message);//.destinationName, ' -- ', message.payloadString);
};
var options = {
timeout: 3,
onSuccess: function () {
alert("mqtt connected");
// Connection succeeded; subscribe to our topic, you can add multile lines of these
client.subscribe('temp/random', {qos: 1});
//use the below if you want to publish to a topic on connect
message = new Paho.MQTT.Message("Hello");
message.destinationName = "/World";
client.send(message);
},
onFailure: function (message) {
alert("Connection failed: " + message.errorMessage);
}
};
function init() {
client.connect(options);
}
This program worked when I tried to access home.html in te web browser. I could see the log being generated in Mosca's console too. However, as visible, this program wasn't a very neat example. For that reason I tried to make a few changes to make the code readable.
This is my code after I made the changes -
home.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="mqttws31.js" type="text/javascript"></script>
<script src="client.js">
</script>
</head>
<body onload="init();">
</body>
</html>
client.js
var wsbroker = "127.0.0.1";
var wsport = 3000
var client = new Paho.MQTT.Client(wsbroker, wsport,"myclientid_" + parseInt(Math.random() * 100, 10));
function onMessageArrived(message) {
document.write(message.payload);
};
function onSuccess() {
document.write("Connected");
client.subscribe('temp/random');
};
function onFailure(message) {
document.write("Connection Failed. Error : " + message.errorMessage);
};
function onConnectionLost(message) {
document.write("Connection Lost. Error : " + message.errorMessage);
};
var options = {
timeout: 3,
onSuccess: onSuccess,
onFailure = onFailure
};
function init() {
client.connect(options);
client.onMessageArrived = onMessageArrived,
client.onConnectionLost = onConnectionLost,
};
I have got a Python script running which publishes value. However, no output is being generated. I checked the Mosca console and noted that no new connections were made. I have just started learning Javascript. I am not sure if my new code is syntactically correct.
Couple changes will fix this.
First, you have onFailure = instead of onFailure:
Next, you want to set your client.onMessageArrived and client.onConnectionLost before you call connect, not after.
Those 2 changes result in
var wsbroker = "127.0.0.1";
var wsport = 3000
var client = new Paho.MQTT.Client(wsbroker, wsport,"myclientid_" + parseInt(Math.random() * 100, 10));
function onMessageArrived(message) {
document.write(message.payload);
};
function onSuccess() {
document.write("Connected");
client.subscribe('temp/random');
};
function onFailure(message) {
document.write("Connection Failed. Error : " + message.errorMessage);
};
function onConnectionLost(message) {
document.write("Connection Lost. Error : " + message.errorMessage);
};
var options = {
timeout: 3,
onSuccess: onSuccess,
onFailure: onFailure,
};
function init() {
console.log('connecting')
client.onMessageArrived = onMessageArrived,
client.onConnectionLost = onConnectionLost,
client.connect(options);
};
I am new to wqtt server. I am trying to connect to mosquitto test server using mqtt.js reffering an example provided on their website.
But i am not able to connect to the server. I always get following error:
WebSocket connection to 'ws://test.mosquitto.org/:8080/mqtt' failed: Error in connection establishment: net::ERR_NAME_NOT_RESOLVED.
Please help. Below is my html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="http://www.hivemq.com/demos/websocket-client/js/mqttws31.js" type="text/javascript"></script>
<title>HiveMQ MQTT Websocket Demo App</title>
<script type="text/javascript">
var client = new Messaging.Client("test.mosquitto.org", 8080, "myclientid_" + parseInt(Math.random() * 100, 10));
//Gets called if the websocket/mqtt connection gets disconnected for any reason
client.onConnectionLost = function (responseObject) {
//Depending on your scenario you could implement a reconnect logic here
alert("connection lost: " + responseObject.errorMessage);
};
//Gets called whenever you receive a message for your subscriptions
client.onMessageArrived = function (message) {
//Do something with the push message you received
$('#messages').append('Topic: ' + message.destinationName + ' | ' + message.payloadString + '');
};
//Connect Options
var options = {
timeout: 3,
//Gets Called if the connection has sucessfully been established
onSuccess: function () {
alert("Connected");
},
//Gets Called if the connection could not be established
onFailure: function (message) {
document.write("Connection failed: " + message.errorMessage);
alert("Connection failed: " + message.errorMessage);
}
};
//Creates a new Messaging.Message Object and sends it to the HiveMQ MQTT Broker
var publish = function (payload, topic, qos) {
//Send your message (also possible to serialize it as JSON or protobuf or just use a string, no limitations)
var message = new Messaging.Message(payload);
message.destinationName = topic;
message.qos = qos;
client.send(message);
}
</script>
</head>
<body>
<button onclick="client.connect(options);">1. Connect</button>
<button onclick="client.subscribe('testtopic/#', {qos: 2}); alert('Subscribed');">2. Subscribe</button>
<button onclick="publish('Hello Foo !','testtopic/bar',2);">3. Publish</button>
<button onclick="client.disconnect();">(4. Disconnect)</button>
<div id="messages"></div>
</body>
From your error message I can see 2 issues.
test.mosquitto.org listens for Websocket connections on 8080 not 1883
There should be no http:// in the url to connect to a websocket server
Also the error message does not match the details you have included in the code sample.