I`m using laravel Event broadcasting , socket.io , node.js , and redis to pass notifications to the client side in real time.
The code is fairly simple, when i make a get request to '/' on the server an event will be fired and some data will be broadcast to all browsers(client side) which listening to this event on a channel(test-Channel).
The Routes.php content:
Route::get('/', 'uses' => function () {
Event::fire( new App\Events\UserHasRegistered('DummyData') );
return view('test');
}]);
The UserHasRegistered Event class :
class UserHasRegistered extends Event implements ShouldBroadcast{
use SerializesModels;
public $name;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($name){
$this->name = $name;
}
/**
* Get the channels the event should be broadcast on.
*
* #return array
*/
public function broadcastOn(){
return ['test-channel'];
}
}
The node Server file content :
/*General Configurations :
- Setting up the node Server
- Server side Socket.io
- node js Redis Client
- instance of ioredis
*/
var server = require('http').Server();
var io = require('socket.io')(server);
var Redis = require('ioredis');
var redis = new Redis();
/*listen to a channel , and when a Message Arrives we send it to All Listening clients via socket.io*/
redis.subscribe('test-channel');
redis.on('message' , function(channel , message){
message = JSON.parse(message);
// The Client Side Channel naming conversion => channelName:EventPublishedToServer => testChannel:UserHasRegistered
io.emit(channel + ':' + message.event , message.data );
});
/*Booting Up the Server : port 3000 */
server.listen(3000 , function(){
console.log('The Server Is Running');
});
Every thing is working fine and the data is passed to the the node server through redis but on the client side where i use socket.io to listen to a specific channel , i get this weird error
GET http://192.168.10.10:3000/socket.io/?EIO=3&transport=polling&t=1446018378941-633 net::ERR_CONNECTION_REFUSED
The Client side :
<script type="text/javascript" src="/js/socket.io.js"></script>
<script>
/*Homestead IP Address , Port:3000 Node Server Port*/
var socket = io('http://192.168.10.10:3000');
/*When Data is sent to client side*/
socket.on('test-channel:App\\Events\\UserHasRegistered' , function(data){
console.log(data);
//$('ul').append('<li><h5>'+ data.name +'</h5></li>');
});
</script>
I`m Using Windows 10 and Homestead virtual box.
any Help ?
i had this same issue and i solved it opening port 3000 in VirtualBox. For that, you should go into homestead settings inside adn then Network->Port Forwarding and there put 3000 on both ports.
did you try to ssh by "vagrant ssh" to your virtual machine and start your server-file from there? A had the same problem while i was starting my server file from windows- or git-command
Did you try
<script type="text/javascript" src="/js/socket.io.js"></script>
<script>
/*Homestead IP Address , Port:3000 Node Server Port*/
var socket = io.connect('http://192.168.10.10:3000');
/*When Data is sent to client side*/
socket.on('test-channel:App\\Events\\UserHasRegistered' , function(data){
console.log(data);
//$('ul').append('<li><h5>'+ data.name +'</h5></li>');
});
</script>
Related
i have a docker compose that contains 3 containers " node-red , influxdb , a html with JavaScript webpage with nginx:alpine image "
in the html and JavaScript webpage i have a list of images and i change the image according to the data that come from node red via websockets
and i receive my data with this JavaScript function
function startConnect() {
document.getElementById('dt').click();
socket = new WebSocket("ws://mywebsite.com:1880/ws/test");
socket.onmessage = function(e) {onMessageArrived(e.data)}
console.log("connected");
socket.onopen = function() {socket.send("1")};
}
// Called when a message arrives
function onMessageArrived(message) {
console.log("onMessageArrived: " + message);
var obj = JSON.parse(message);
document.getElementById("image1").src = "myimage/" + obj.L + "_DL.png";
document.getElementById("image2").src = "myimage/" + obj.M + obj.F + obj.S + "_" + obj.Z48_70 + "_M.png";
document.getElementById("image3").src = "myimage"+ obj.V + obj.V + "_X";
}
every thing worked fine until i have decided to use docker for "node-red and influx and the html webpage" and use nginxwithout docker with letsencrypt certifacts to handle the reverse proxy of my 3 containers.
The problem that i am facing is that i cannot receive data with websockets even though i change the socket = new WebSocket("ws://mywebsite.com:1880/ws/test") to socket = new WebSocket("ws://mywebsite.com:6100/ws/test") the port 6100 used by my webpage contain with this i am having an https error and with socket = new WebSocket("ws://192.170.0.6:6100/ws/test") the IP address of my webpage container and also with new WebSocket("ws://mywebsite/webpage/ws/test") this is handeled by nginx to route it the IP and the port used by my webpage container
If you are connecting to a WebSocket address that is being boot strapped via HTTPS then you need to use the wss: scheme rather than ws:
So if you have enabled https on port 6100 then you need to use wss://mywebsite.com:6100/ws/test
(also if you are using nginx as a reverse proxy is there any reason not to use the default ports of 80 and 443 for http/https respectively?)
EDIT:
If your proxy is presenting the default ports of 80/443 for http/https respectively then you should be using something like the following:
function startConnect() {
document.getElementById('dt').click();
if (location.scheme === 'http:' ) {
socket = new WebSocket("ws://mywebsite.com/ws/test");
} else {
socket = new WebSocket("wss://mywebsite.com/ws/test");
}
socket.onmessage = function(e) {onMessageArrived(e.data)}
console.log("connected");
socket.onopen = function() {socket.send("1")};
}
This will pick ws:// or wss:// depending on how the page is loaded (http vs https)
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 have made small reasearch about patterns supported by zeromq. I would like to describe problem with PUB/SUB pattern, but probably I discover this problem in my recent project also in PUSH/PULL pattern. I use NodeJS zeromq implementation.
I prepare two examples (server.js & client.js). I recognized that first message from server.js is lost every time I restart server (message is send every 1 second). client.js doesn't get first message. It is probably caused by to short time before sending messages. When I start sending messages after some time (e.g. 1 second) everything works fine. I thing that zmq needs some time for initialization connection between publisher and subscriber.
I would like to know when producer (server) is ready to sending messages for subscribed clients. How get this information?
I don't understand why client.js connected and subscribed for messages doesn't get it, because server is not ready for support subscriptions after restart.
Maybe it works like this by design.
server.js:
var zmq = require('zmq');
console.log('server zmq: ' + zmq.version);
var publisher = zmq.socket('pub');
publisher.bindSync("tcp://*:5555");
var i = 0;
var msg = "get_status OK ";
function sendMsg () {
console.log(msg + i);
publisher.send(msg + i);
i++;
setTimeout(sendMsg, 1000);
}
sendMsg();
process.on('SIGINT', function() {
publisher.close();
process.exit();
});
client.js:
var zmq = require('zmq');
console.log('client zmq: ' + zmq.version);
var subscriber = zmq.socket('sub');
subscriber.subscribe("get_status");
subscriber.on('message', function(data) {
console.log(data.toString());
});
subscriber.connect("tcp://127.0.0.1:5555");
process.on('SIGINT', function() {
subscriber.close();
process.exit();
});
In the node zmq lib repo you have stated the supported monitoring events. Subscribing to this will allow you to monitor your connection, in this case the accept event. However don't forget that you'll also have to call the monitor() function on the socket to activate monitoring.
You should end up with something like:
var publisher = zmq.socket('pub');
publisher.on('accept', function(fd, ep) {
sendMsg();
});
publisher.monitor(100, 0);
publisher.bindSync("tcp://*:5555");
I am using hapijs in my MEAN stack and implemented socket.io (using this for reference: http://matt-harrison.com/using-hapi-js-with-socket-io/) Everything works fine, no problems there. It works great in my application!
However, there will be script I will be running via command line separately (which will be doing some maintenance on the application) that I was hoping to connect to the same web socket and be able to push to clients messages if data needs to be refreshed.
My index.js taken straight from the example:
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 3000 });
var io = require('socket.io')(server.listener);
io.on('connection', function (socket) {
socket.emit('Hello');
});
server.start();
I tried to create a separate JS file, and do a:
var socket = require('socket.io');
var io = socket.listen(3000);
Then passed io to send a message. This doesn't seem right... I guess I'm wondering if this can even be done. Messing around I've either created a separate web socket or no connection to the client.
Please let me know if I need to provide more information.
Thanks.
T
In your provided code, you're creating 2 servers. [io.listen()][1] listens on a port as a server.
What you need to do instead to pass messages around is to create a socket.io client in your separate script. There's a separate module for this called socket.io-client, which you can require to be a client:
client.js
var io = require('socket.io-client');
var socket = io('http://localhost:3000');
socket.on('beep', function () {
console.log('beep');
socket.emit('boop');
});
server.js
Here's a slightly updated version of your server script too (hapi v9.0.0 has a mandatory callback for server.start()):
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 3000 });
var io = require('socket.io')(server.listener);
io.on('connection', function (socket) {
socket.emit('beep');
socket.on('boop', function () {
console.log('boop');
});
});
server.start(function () {
console.log('Started Server!');
});
If you open up a couple of terminals and run these, you should see messages passed between them and beep and boop logged out:
WebSocket Error: Network Error 12031, The connection with the server was reset
I want to subscribe for mqtt message from UI. I am using the following code. I have mosquitto broker running on my machine, so I have given the url as my IP and it is listening on port number 1883, I have given some random Client ID
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<script src="../bower_components/jquery/dist/jquery.min.js"></script>
<script src="../bower_components/jquery/dist/jquery.js"></script>
<script src="../paho.javascript-1.0.1/mqttws31-min.js"></script>
<script src="../paho.javascript-1.0.1/mqttws31.js"></script>
<script src="../js/browserMqtt.js"></script>
<script>
// Create a client instance
client = new Paho.MQTT.Client("10.9.177.110", 1883, "100");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
client.connect({onSuccess:onConnect});
// called when the client connects
function onConnect() {
console.log("onConnect");
client.subscribe("/World");
message = new Paho.MQTT.Message("Hello");
message.destinationName = "/World";
client.send(message);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
console.log("onMessageArrived:"+message.payloadString);
}
</script>
</body>
</html>
What type of broker are you trying to connect to? Apart from the IBM MessageSight appliance I'm not aware of any other brokers that can share the same port for both native MQTT and MQTT over Websockets.
Since port 1883 is traditionally used for native MQTT have you remembered to add a new listener for MQTT over Websockets?
Assuming you are using mosquitto 1.4.x then you need to add something like this to your config file:
listerner 1884
protocol websockets
This will add a Websocket listener on port 1884
Can you confirm that you are running a version of Mosquitto with WebSockets enabled?