These are my goals.
connect to websocket API as a client
output these websocket messages to a specified browser DOM(client-side)
.
connecting to websocket on nodeJS
const WebSocket = require('ws');
const url = 'wss://websocket.example';
const ws = new WebSocket(url);
ws.onmessage = (event) => {
wsMessages = JSON.parse(event.data);
wsMessagesTime = wsMessages.t;
wsMessagesData = wsMessages.d;
console.log(wsMessagesTime, wsMessagesData);
};
from here I can console.log the wsMessagesTime and wsMessagesData during every event and I can see the live feed from my nodemon.
Now I would like to output that to my browser dom element.
output these websocket messages to a specified browser DOM(client-side)
const {log, error } = console;
const express = require('express');
const path = require('path');
const server = app.listen(3000, log('server is running on 3000'));
app.use(express.static('./public'));
app.get('/', (req,res) => {
console.log('root page logged')
})
from here, I put my index.html file inside the ./public directory.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>websocket testing</title>
<script> var exports = {};</script>
</head>
<body>
<h2>hi this is a test string</h2>
<div id="websocket data"></div>
</body>
</html>
From here, I want to render my websocket data feeds onto the div element with the id websocket data.
From my research express is server side so I dont have access to the DOM
even view engines like ejs doesn't let me put data into the specified DOM. (correct me if I'm wrong please)
I simply want to render the output from console.log(wsMessagesTime, wsMessagesData); to the local webpage running on the express server into the div element specified as websocket data.
Related
I need to broadcast my steam in localhost for developing purposes. But the error comes in. I am new to media servers. I just wanna integrate the red5pro media server for one to many broadcasting in my website.
I am currently following Red5pro Publisher Docs and this tutorial from youtube for testing red5pro[beginner to media servers]. The tutorial is little outdated but i am still following it because i didn't find any other tutorial for red5pro.
I am using python simplehttpserver ("python -m http.server 8000") to run local server as told in the video tutorial.
My html code ->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="video-container">
<video id="red5pro-publisher"></video>
</div>
<script src="lib/red5pro/red5pro-sdk.min.js"></script>
<script>
// Create a new instance of the WebRTC publisher.
var publisher = new red5prosdk.RTCPublisher();
// Create a view instance based on video element id.
var view = new red5prosdk.PublisherView('red5pro-publisher');
view.attachPublisher(publisher);
// Access user media.
navigator.getUserMedia({
audio: true,
video: true
}, function (media) {
// Upon access of user media,
// 1. Attach the stream to the publisher.
// 2. Show the stream as preview in view instance.
publisher.attachStream(media);
view.preview(media, true);
}, function (error) {
console.error(error);
});
// Using Chrome/Google TURN/STUN servers.
var iceServers = [{ urls: 'stun:stun2.l.google.com:19302' }];
// Initialize
publisher.init({
protocol: 'ws',
host: 'localhost',
port: 8081,
app: 'live',
streamName: 'mystream',
iceServers: iceServers,
tcpMuxPolicy: 'negotiate'
})
.then(function () {
// Invoke the publish action
return publisher.publish();
})
.catch(function (error) {
// A fault occurred while trying to initialize and publish the stream.
console.error(error);
});
</script>
</body>
<!-- WebRTC Shim -->
<!-- <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script> -->
<!-- Exposes `red5prosdk` on the window global. -->
</html>
The error ->
red5pro-sdk.min.js 158th line -->
createWebSocket: function(e) { return new WebSocket(e) }
I think it is not able to create websocket!!
I'm not an expert on the HTML5 SDK, but I see you have the media settings and a few other lines commented out; uncomment them and try again. Also look through your red5.log on the server for other clues; any exceptions firing would be helpful.
so I've been trying to create a simple web page with Apache made with bootstrap from where I can send/receive publication with Mosquitto.
My issue here is that when I try to connect to the mqtt client i get this errors, i tried every combination that i found looking on guides and other stuff i founded, i either get ERR_CONNECTION_REFUSED or Error 404 or CONNECTION_RESET.
WebSocket connection to 'ws://localhost:9001/mqtt' failed: Error in
connection establishment: net::ERR_CONNECTION_REFUSED
I tried looking up ways to fix this, so I added in /etc/mosquitto/mosquitto.conf:
#listener 8081
#protocol websockets
#listener 8080
#protocol websockets
#port 9001
listener 9001
protocol websockets
My index.php file (at some point i just kept adding stuff):
<head >
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<!-- MQTT Websocket -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.2/mqttws31.js"></script>
<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 = 'localhost';
var port = 9001;
function onConnect() {
message = new Paho.MQTT.Message("Test");
message.destinationName = 'test';
mqtt.send(message);
}
function onFail() {
console.log("fail")
}
function MQTTconnect() {
mqtt = new Paho.MQTT.Client(host, port, '/mqtt', "mark");
var options = {
cleanSession: true,
useSSL: false,
timeout: 3,
onSuccess: onConnect,
onFailure: onFail,
};
mqtt.connect(options);
}
</script>
If anyone could kindly tell me if i missed something or what i have to do to make the connection work I'd gladly appreciate! I've been stuck like this for hours now.
EDIT :
I think I found the issue i think I just had to type on a terminal
sudo mosquitto -c /etc/mosquitto/mosquitto.conf
and leave it open to make it work.
I am new to Node.js and javascript, hence don't have much experience and in need of some help.
I have a script that opens a simple server socket and just listens to incoming connection and prints the incoming message to the screen:
var net = require('net');
var server = net.createServer();
server.on('connection', handleConnection);
server.listen(9000, function() {
console.log('server listening to %j', server.address());
});
function handleConnection(conn) {
var remoteAddress = conn.remoteAddress + ':' + conn.remotePort;
console.log('new client connection from %s', remoteAddress);
conn.on('data', onConnData);
conn.once('close', onConnClose);
conn.on('error', onConnError);
function onConnData(d) {
var chunks = [];
chunks.push(d);
console.log('Client at %s says %s', remoteAddress, Buffer.concat(chunks).toString());
conn.write(d);
}
function onConnClose() {
console.log('connection from %s closed', remoteAddress);
}
function onConnError(err) {
console.log('Connection %s error: %s', remoteAddress, err.message);
}
}
I have tested it and it works when i run it from the IDE (eclipse).
What I am trying to do is to incorporate this code inside an HTML file.
The HTML file does not suppose to be accessed from the out side, its for learning purposes only.
Basically i would like to open the HTML file, it should run the code in the background (listen to the socket) and once the is a connection and data coming in it should print it on the screen (sing alert for example).
The HTML code looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>some title</title>
</head>
<body>
<script
type = "text/javascript" src = "simple_server.js">
</script>
</body>
</html>
While trying to open the HTML file using a browser or inside eclipse it does nothing.
My question is, is it even possible? If it is, what am i doing wrong and how may I fix it?
Any help would be appreciated. Thank you.
i have a device that send data strings via mqtt to my mosquitto broker on ubuntu i currently use node-red to then receive these strings and use javascript function node to do everything else i need, data conversions, insert into query etc but that one thing im struggling with is i want to move away from node-red so i just have files with pure code, i have tried the code provided on npm website but i need an idiots guide haha does anyone have any idea's where i can look or anyone able to help me ? all my html files are currently displayed from an apache server
my current set up for mqtt is mosquito running on ubuntu i have enabled websockets in the configuration files with listner of 1883
mosquitto configuration
listener 1883
listener 1884
protocol websockets
pid_file /var/run/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d
mqtt code i have tried :
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script> <script type="text/javascript">
var wsbroker = "localhost"; //mqtt websocket enabled broker
var wsport = 1883 // port for above
var client = new Paho.MQTT.Client(wsbroker, wsport,
"myclientid_" + parseInt(Math.random() * 100, 10));
client.onConnectionLost = function (responseObject) {
console.log("connection lost: " + responseObject.errorMessage);
};
client.onMessageArrived = function (message) {
console.log(message.destinationName, ' -- ', message.payloadString);
};
var options = {
timeout: 3,
onSuccess: function () {
console.log("mqtt connected");
client.subscribe('/tracked', {qos: 1});
},
onFailure: function (message) {
console.log("Connection failed: " + message.errorMessage);
}
};
function init() {
client.connect(options);
}
</head>
<body onload="init();">
</body>
So as mentioned in the comments.
You are trying to connect to port 1883 which is the native MQTT port.
To use the Javascript client from a webpage you need to use MQTT over Websockets, you have added a Websocket listener on port 1884.
So you need to edit the code as follows:
var wsbroker = "localhost"; //mqtt websocket enabled broker
var wsport = 1884 // Websocket port for above
var client = new Paho.MQTT.Client(wsbroker, wsport,
"myclientid_" + parseInt(Math.random() * 100, 10));
I'm trying to learn JavaScript and following Daniel Shiffman's p5.js tutorial. I made a fun little pong game and wanted it to take it to the next level by making it multiplayer. I want to start with the basics and just follow Daniel's Socket tutorial. I can successfully access my site and see my canvas. However, I want to take it to the next level by making it available over the LAN. I am not sure how to do this, and I am having some trouble. Here is the client code I used:
var socket;
function setup() {
socket = io.connect();
createCanvas(200, 200);
}
function draw() {
background(0);
fill(255);
ellipse(mouseX, mouseY, 60, 60);
}
The server code is:
// Imports
var express = require('express');
var socket = require('socket.io');
// Create Local host
var app = express();
var server = app.listen('3000')
app.use(express.static('public'));
// Sockets
var io = socket(server);
io.sockets.on('connection', newConnection);
// New Connection
function newConnection(socket) {
console.log("New Connection: " + socket.id);
}
console.log("Server running...");
if needed here is my index.html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Learning Sockets</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script src="/libraries/addons/p5.min.js"></script>
<script src="/libraries/addons/p5.dom.min.js"></script>
<script src="/libraries/addons/p5.sound.min.js"></script>
<script src="sketch.js"></script>
<script src="/libraries/addons/p5.dom.js"></script>
</head>
<body>
</body>
</html>
Keep in mind that I am a beginner. I have tried looking at other posts, but the answers were too complicated, and in the end, I don't think that it solved my problem. Not sure if it matters but I do have node.js, express, and socket.io installed. I have tried connecting by using http://my-ip:3000. I can connect from my computer via localhost:3000 and my-IP:3000. But when I try to connect from another computer it doesn't work. And yes I am connected to the same network.
Daniel Shiffman's playlist: https://www.youtube.com/playlist?list=PLRqwX-V7Uu6b36TzJidYfIYwTFEq3K5qH
Sorry, I looked at my IP address again, and I used the wrong one. Silly me. PROBLEM SOLVED :D