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);
};
Related
Right now I am using Node.js to Javascript to take the microphone audio data from 1 user and to have other people listen to that user's mic audio via browser. I am trying to do this right now with socket.io. How can I achieve this? right now I can send messages but not audio or a simple audio file. It would be awesome if I can livestream the user's microphone audio. Any simple client/server code example would be so appreciated. I've been reading about this for hours and everything seems so confusing. If the problem is too hard, I also have a wav file, but how can I send that? Please help please!
Here is my current code.
Server.js
var http = require("http");
var io = require('socket.io');
var server = http.createServer(function (request, response) {
response.writeHead(200, {
"Content-Type": "text/html"
});
response.write("WebSocket Start~~~~~~~~~~~~");
response.end("");
}).listen(8080);
var socket = io.listen(server);
socket.on('connection', function (client) {
client.on('client-stream-request', function (data) {
var stream = ss.createStream();
var filename = __dirname + '/downloads/' + < YOURSONG.MP3 > ;
ss(socket).emit('audio-stream', stream, {
name: filename
});
fs.createReadStream(filename).pipe(stream);
});
client.on('message', function (event) {
console.log('Received message from client!', event);
client.receive audio from user 1 browser mic ? ? ? ? ? ? ? ?
client.emit('emitMessage', {
hello: 'messgge received, wish you happy' + new
Date().toString()
});
});
client.on('disconnect', function () {
// clearInterval(interval);
console.log('Server has disconnected');
});
client.send('hello, I am the server');
client.send user 1 browser mic audio to everyone connected to the server ? ? ? ? ? ?
});
Here is my client code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
div {
border-radius: 10px;
border: 2px solid pink;
width: 800px;
}
</style>
</head>
<body>
<h1></h1>
<div id="result"></div>
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script>
//创建Socket.IO实例,建立连接
var socket = io.connect('http://localhost:8080');
var audio = document.getElementById('player');
ss(socket).on('audio-stream', function (stream, data) {
parts = [];
stream.on('data', function (chunk) {
parts.push(chunk);
});
stream.on('end', function () {
audio.src = (window.URL || window.webkitURL).createObjectURL(new Blob(parts));
audio.play();
});
});
// 添加一个连接监听器
socket.on('connect', function () {
console.log('Client has connected to the server!');
});
// 添加一个连接监听器
socket.on('message', function (data) {
document.getElementById("result").innerHTML += data + "<br />";
});
socket.on('emitMessage', function (data) {
document.getElementById("result").innerHTML += data.hello + "<br />";
});
// 添加一个关闭连接的监听器
socket.on('disconnect', function () {
console.log('The client has disconnected!');
});
// 通过Socket发送一条消息到服务器
function sendMessageToServer(message) {
socket.send(message);
}
var date = new Date();
var ms = "Time: " + date.toString() + "Today is a nice day, wish you happy";
setInterval("sendMessageToServer(ms)", 1000);
</script>
</body>
</html>
I have webrtc / socket.io / nodejs running on a server, everything works fine when i go to the https://domain.com:8080 to test a video conference.
But i want the script to run in my webserver /public_html/
But i dont know why it is not connecting to the 8080 server.
"socket.io.js GET https://domain.com/socket.io/?EIO=3&transport=polling&t=LPgZs2K 404 (Not Found)"
my server (server.js)
// Load required modules
var https = require("https"); // http server core module
var express = require("express"); // web framework external module
var serveStatic = require('serve-static'); // serve static files
var socketIo = require("socket.io"); // web socket external module
var easyrtc = require("../");
const fs = require('fs'); // EasyRTC external module
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
// Set process name
process.title = "node-easyrtc";
// Setup and configure Express http server. Expect a subfolder called "static" to be the web root.
var app = express();
app.use(serveStatic('static', {'index': ['index.html']}));
// Start Express http server on port 8080
var webServer = https.createServer(options, app).listen(8080);
// Start Socket.io so it attaches itself to Express server
var socketServer = socketIo.listen(webServer, {"log level":1});
easyrtc.setOption("logLevel", "debug");
// Overriding the default easyrtcAuth listener, only so we can directly access its callback
easyrtc.events.on("easyrtcAuth", function(socket, easyrtcid, msg, socketCallback, callback) {
easyrtc.events.defaultListeners.easyrtcAuth(socket, easyrtcid, msg, socketCallback, function(err, connectionObj){
if (err || !msg.msgData || !msg.msgData.credential || !connectionObj) {
callback(err, connectionObj);
return;
}
connectionObj.setField("credential", msg.msgData.credential, {"isShared":false});
console.log("["+easyrtcid+"] Credential saved!", connectionObj.getFieldValueSync("credential"));
callback(err, connectionObj);
});
});
// To test, lets print the credential to the console for every room join!
easyrtc.events.on("roomJoin", function(connectionObj, roomName, roomParameter, callback) {
console.log("["+connectionObj.getEasyrtcid()+"] Credential retrieved!", connectionObj.getFieldValueSync("credential"));
easyrtc.events.defaultListeners.roomJoin(connectionObj, roomName, roomParameter, callback);
});
// Start EasyRTC server
var rtc = easyrtc.listen(app, socketServer, null, function(err, rtcRef) {
console.log("Initiated");
rtcRef.events.on("roomCreate", function(appObj, creatorConnectionObj, roomName, roomOptions, callback) {
console.log("roomCreate fired! Trying to create: " + roomName);
appObj.events.defaultListeners.roomCreate(appObj, creatorConnectionObj, roomName, roomOptions, callback);
});
});
//listen on port 8080
webServer.listen(8080, function () {
console.log('listening on http://localhost:8080');
});
my html file on de WEB server. structure like this https://domain.com/test.html
<!DOCTYPE html>
<html>
<head>
<title>EasyRTC Demo:EasyRTC Demo: Video+Audio HD 720</title>
<link rel="stylesheet" type="text/css" href="/easyrtc/easyrtc.css" />
<script src="js/socket.io.js"></script>
<script type="text/javascript" src="js/easyrtc.js"></script>
<script type="text/javascript" src="js/video.js"></script>
<script>
var selfEasyrtcid = "";
function connect() {
easyrtc.setVideoDims(1280,720);
easyrtc.enableDebug(false);
easyrtc.setRoomOccupantListener(convertListToButtons);
easyrtc.easyApp("easyrtc.videoChatHd", "selfVideo", ["callerVideo"], loginSuccess, loginFailure);
}
function clearConnectList() {
var otherClientDiv = document.getElementById("otherClients");
while (otherClientDiv.hasChildNodes()) {
otherClientDiv.removeChild(otherClientDiv.lastChild);
}
}
function convertListToButtons (roomName, data, isPrimary) {
clearConnectList();
var otherClientDiv = document.getElementById("otherClients");
for(var easyrtcid in data) {
var button = document.createElement("button");
button.onclick = function(easyrtcid) {
return function() {
performCall(easyrtcid);
};
}(easyrtcid);
var label = document.createTextNode(easyrtc.idToName(easyrtcid));
button.appendChild(label);
button.className = "callbutton";
otherClientDiv.appendChild(button);
}
}
function performCall(otherEasyrtcid) {
easyrtc.hangupAll();
var acceptedCB = function(accepted, caller) {
if( !accepted ) {
easyrtc.showError("CALL-REJECTED", "Sorry, your call to " + easyrtc.idToName(caller) + " was rejected");
}
};
var successCB = function() {};
var failureCB = function() {};
easyrtc.call(otherEasyrtcid, successCB, failureCB, acceptedCB);
}
function loginSuccess(easyrtcid) {
selfEasyrtcid = easyrtcid;
document.getElementById("iam").innerHTML = "I am " + easyrtc.cleanId(easyrtcid);
}
function loginFailure(errorCode, message) {
easyrtc.showError(errorCode, message);
}
// Sets calls so they are automatically accepted (this is default behaviour)
easyrtc.setAcceptChecker(function(caller, cb) {
cb(true);
} );
</script>
</head>
<body onload="connect();">
<h1>EasyRTC Demo: Video+Audio HD 720p</h1>
<div id="demoContainer">
<div>
Note: your own image will show up postage stamp sized, while the other party"s video will be shown in high-definition (1280x720). Note: not all webcams are seen by WebRTC as providing high-definition video; the fallback is to use standard definition (640x480).
</div>
<div id="connectControls">
<div id="iam">Not yet connected...</div>
<br />
<strong>Connected users:</strong>
<div id="otherClients"></div>
</div>
<div id="videos">
<div style="position:relative;float:left;" width="1282" height="722">
<video autoplay="autoplay" id="callerVideo"></video>
<video class="easyrtcMirror" autoplay="autoplay" id="selfVideo" muted="true" volume="0" ></video>
</div>
<!-- each caller video needs to be in it"s own div so it"s close button can be positioned correctly -->
</div>
</div>
</body>
</html>
Socket.io.js: http://81.171.38.245/js/socket.io.js
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 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.
I have been trying my hand at node.js and socket.io, and following a tutorial. I keep getting an error from an application i am building. This is my server.js file:
var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {};
var chatServer = require('./lib/chat_server.js');
chatServer.listen(server);
//file doesn't exist
function send404(response) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('Error 404: resource not found.');
response.end();
}
//handles serving file data
function sendFile(response, filePath, fileContents) {
response.writeHead(
200,
{"content-type": mime.lookup(path.basename(filePath))}
);
response.end(fileContents);
}
//cache static files to memory
function serveStatic(response, cache, absPath) {
if (cache[absPath]) {
sendFile(response, absPath, cache[absPath]);
} else {
fs.exists(absPath, function(exists) {
if (exists) {
fs.readFile(absPath, function(err, data) {
if (err) {
send404(response);
}
else {
cache[absPath] = data;
sendFile(response, absPath, data);
}
});
}
else {
send404(response);
}
});
}
}
var server = http.createServer(function(request, response) {
var filePath = false;
if (request.url == '/') {
filePath = 'public/index.html';
}
else {
filePath = 'public' + request.url;
}
var absPath = './' + filePath;
serveStatic(response, cache, absPath);
});
server.listen(3001, function() {
console.log("Server listening on port 3001.");
});
This is my index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Chat</title>
<meta name="description" content="An interactive chat application using websockets.">
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<div id='content'>
<div id='room'></div>
<div id='room-list'></div>
<div id='messages'></div>
<form id='send-form'>
<input id='send-message' />
<input id='send-button' type='submit' value='Send'/>
<div id='help'>
Chat commands:
<ul>
<li>Change nickname: <code>/nick [username]</code></li>
<li>Join/create room: <code>/join [room name]</code></li>
</ul>
</div>
</form>
</div>
<script src="[localserver here]:3001/socket.io/socket.io.js" type="text/javascript"></script>
<script src="/javascripts/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="/javascripts/chat.js" type="text/javascript"></script>
<script src="/javascripts/chat_ui.js" type="text/javascript"></script>
</body>
</html>
Upon loading "[localserver here]:3001" from the browser, the index page appears with the ensuing CSS. But when i try an event, like sending a message, i get this error:
Error 404: resource not found.
I right-clicked and inspected element from my Chrome browser and got this two messages:
Failed to load resource: the server responded with a status of 404 (Not Found) "[localserver here]:3001/socket.io/socket.io.js"
Uncaught ReferenceError: io is not defined "[localserver here]:3001/javascripts/chat_ui.js:26"
This is line 26 from my chat_ui.js file:
var socket = io.connect('[localserver here]:3001');
$(document).ready(function() {
var chatApp = new Chat(socket);
socket.on('nameResult', function(result) {
var message;
if (result.success) {
message = 'You are now known as ' + result.name + '.';
} else {
message = result.message;
}
$('#messages').append(divSystemContentElement(message));
});
socket.on('joinResult', function(result) {
$('#room').text(result.room);
$('#messages').append(divSystemContentElement('Room changed.'));
});
socket.on('message', function (message) {
var newElement = $('<div></div>').text(message.text);
$('#messages').append(newElement);
});
socket.on('rooms', function(rooms) {
$('#room-list').empty();
for(var room in rooms) {
room = room.substring(1, room.length);
if (room != '') {
$('#room-list').append(divEscapedContentElement(room));
}
}
$('#room-list div').click(function() {
chatApp.processCommand('/join ' + $(this).text());
$('#send-message').focus();
});
});
setInterval(function() {
socket.emit('rooms');
}, 1000);
$('#send-message').focus();
$('#send-form').submit(function() {
processUserInput(chatApp, socket);
return false;
});
})
I have tried all sorts. Initially line 26 was var socket = io.connect(); and i changed it to the one above. I also changed the directory of socket.io.js in the index.html file from:
to
...as i thought this was the problem, but it is still giving me the same error.
Please how do i resolve this?
(PS - I am using Brackets as my IDE for node.js development. Also, i used "[localserver]" to indicate the localhost)
Try this:
<script type="text/javascript" src='http://localhost:3001/socket.io/socket.io.js'>
</script>
<script type="text/javascript">
var socket = io.connect('http://localhost:3001');
socket.on('connect',function(){
console.log("connect");
});
</script>
It must help you.
The line chatServer.listen(server); should be after you run your server.
chartServer is listening to the server but that one is not running yet.
Try to move this line:
chatServer.listen(server);
to the end of your script server.js