I've setup my slanger server correctly. It runs but when I connect from the browser it complains about the app key not being found? but my app_key and key are the same...
I send events like so in python
p = pusher.Pusher(app_id='mysite', key='mysite', secret='secretstuff', host='slanger.mysite.com', port='4567')
I run the slanger server like this:
slanger -k mysite -s secretstuff
Running Slanger v.0.4.0
Slanger API server listening on port 4567
Slanger WebSocket server listening on port 8080
This is what the browser outputs
WebSocket connection to
'wss://slanger.mysite.com:8080/app/mysite?protocol=7&client=js&version=2.2.3&flash=false'
failed: Error in connection establishment: net::ERR_CONNECTION_CLOSED
pusher.min.js:12 Pusher : Error :
{"type":"WebSocketError","error":{"type":"PusherError","data":{"code":4001,"message":"Could
not find app by key mysite. Perhaps you're connecting to the wrong
cluster."}}}
here's my JS code:
Pusher.host = 'slanger.mysite.com'
Pusher.app_id = 'mysite'
Pusher.ws_port = 8080
Pusher.wss_port = 8080
var pusher = new Pusher('mysite');
var channel = pusher.subscribe("test");
channel.bind('update', function (data) {
console.log(data.message);
});
It looks like you forgot to add wsHost config option.
I got the same issue as you, and this worked for me.
Following slanger documentation, you should do it like this:
Pusher.host = 'slanger.example.com'
Pusher.port = 4567
var pusher = new Pusher('#{Pusher.key}', {
wsHost: "0.0.0.0",
wsPort: "8080",
wssPort: "8080",
enabledTransports: ['ws', 'flash']
});
Related
We are developing a WebSocket server using Nodejs with socket.io
I have used createServer method from class HTTP and then listen to a port as follows :
var server = http.createServer();
server.listen(port, function () {
...
}
Now The problem is that I only have the service name
and listening to a service doesn't work :
var server = http.createServer();
server.listen(service, function () {
...
}
So I need to read and parse the file /etc/services to get the port associated with the service as follows :
var str = fs.readFileSync(filename).toString();
var serviceline = str.match( port+".*tcp" );
var port = serviceline[0].match( "[0-9]+" )
Is there a simpler way to get the port from the service?
Thanks in advance
Jean-Marie
You can use find-process to find port from process or vice-versa
Command line usage
npm install find-process -g
Usage: find-process [options] <keyword>
Options:
-V, --version output the version number
-t, --type <type> find process by keyword type (pid|port|name)
-p, --port find process by port
-h, --help output usage information
Examples:
$ find-process node # find by name "node"
$ find-process 111 # find by pid "111"
$ find-process -p 80 # find by port "80"
$ find-process -t port 80 # find by port "80"
Code usage
npm install find-process --save
const find = require('find-process');
find('pid', 12345)
.then(function (list) {
console.log(list);
}, function (err) {
console.log(err.stack || err);
})
I have used this to find process from the port but I think it provides a reverse way to or you can skim down to its repo and pick the code you needed.
I don't need a server port but the port corresponding to a service name
for instance having the following service "wsgw" specified in file /etc/services
wsgw 8001/tcp # websocket gateway
I need to get the value 8001 before running the server listening to this port this way :
var server = http.createServer();
server.listen(8001, function () {
...
listening to a service as below doesn't work :
var server = http.createServer();
server.listen("wsgw", function () {
...
note : finding a port from a process doesn't help me as it is not a process but a service
I built mosquitto on CentOS7 and a node.js client based on mqtt.js,installing with
yum install mosquitto mosquitto-clients
The local test
> mosquitto_sub -h localhost -t test
> mosquitto_pub -h localhost -t test -m "hello world"
works fine, but when I ran:
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://192.168.1.70')
client.on('connect', function () {
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
I got Error: Connection refused: Not authorized
The mosquitto.conf is like:
pid_file /var/run/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
allow_anonymous true
and I use systemctl restart mosquitto to restart it several time, which doesn't help. The firewall is down and log file stays empty.
A screenshot on status:
Can anyone help please?
UPDATE:
It turns out that the mosquitto service is somehow broken as the status shows Active: active (exited).
I use mosquitto -p 1884 -v cmd to run another mosquitto process on port 1884, it works fine. Then I try to reload the conf using
> /etc/init.d/mosquitto reload. It gives me
Reloading mosquitto configuration (via systemctl): Job for mosquitto.service invalid.
[FAILED]
So there IS something wrong with mosquitto service.
Not a final solution but I manage to fix this by remove-reboot-install process, the status went green as follow:
SOLUTION
I managed to find out the reason it doesn't work. I've installed rabbitmq on my server, it uses its "rabbitmq_mqtt" which consumes port 1883. Reassigning a port will solve this problem.
I managed to find out the reason. I've installed rabbitmq on my server, it uses its "rabbitmq_mqtt" which consumes port 1883. Reassigning a port will solve this problem. The problem is simple, but yeah, the CLI should have given me more information.
You need to add the authorize information to mqtt connect method.Just like this.
var client=mqtt.connect("ws://192.168.1.1", {
username: "yourUsername",
password: "yourPassword"
}
Add the Authorization details for the client to connect
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://192.168.1.70', {
username: '<username>',
password: '<password>'
});
client.on('connect', function () {
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
I am trying to run a node js app on Heroku using WebSockets. However, I am not able to resolve this error (As seen in conosle of Chrome browser)
WebSocket connection to 'wss://myappname.herokuapp.com:27225/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I am using 'wss' since Heroku runs on HTTPS.
My client side code is :
$.get("https://myappname.herokuapp.com/port",function(data){
port = data;
console.log(data);
host = 'wss://myappname.herokuapp.com:' + port + '/';
ws = new WebSocket(host);
});
My server side code is :
var WebSocketServer = require("ws").Server
var fs = require('fs');
var express = require('express');
var app = express();
var http = require('http');
var port = process.env.PORT || 5000;
var request = require('request');
var server = http.createServer(app);
var serverOnPort = server.listen(port);
console.log("Server listening on port ",port);
var wss = new WebSocketServer({server: serverOnPort});
console.log("websocket server created");
Any help would be appreciated.
Thank You.
So it seems like I was trying to over-do it with the port number. Just using the host as wss://myappname.herokuapp.com/ works well.
I also found this problem. It seems Heroku will automatically route port number. It does's allow to specify port number in url. In my chrome, it show ERR_CONNECTION_RESET. This also happen with XMLHttpRequest. Port number still need when you test with localhost or another server which is not Heroku.
I have the server running on port 8080, I can see the web interface...
When I try to run this example from command line, like this: node test.js (node version: 4.1.0), I get:
playground/rethink/node_modules/rethinkdb/node_modules/bluebird/js/main/async.js:43
fn = function () { throw arg; };
^
ReqlTimeoutError: Could not connect to localhost:8080, operation timed out.
Why?
I installed RethinkDB via Homebrew and I'm on Mavericks.
I assume you changed the port number in the demo code to 8080?
r.connect({ host: 'localhost', port: 28015 }, ...
don't do that.
Port 8080 is reserved for http administrative connections, while client driver connections go through port 28015. Leave it at port 28015 and try it again.
I'm writing an event-driven publish/subscribe application with NodeJS and Redis. I need an example of how to notify web clients when the data values in Redis change.
OLD only use a reference
Dependencies
uses express, socket.io, node_redis and last but not least the sample code from media fire.
Install node.js+npm(as non root)
First you should(if you have not done this yet) install node.js+npm in 30 seconds (the right way because you should NOT run npm as root):
echo 'export PATH=$HOME/local/bin:$PATH' >> ~/.bashrc
. ~/.bashrc
mkdir ~/local
mkdir ~/node-latest-install
cd ~/node-latest-install
curl http://nodejs.org/dist/node-latest.tar.gz | tar xz --strip-components=1
./configure --prefix=~/local
make install # ok, fine, this step probably takes more than 30 seconds...
curl http://npmjs.org/install.sh | sh
Install dependencies
After you installed node+npm you should install dependencies by issuing:
npm install express
npm install socket.io
npm install hiredis redis # hiredis to use c binding for redis => FAST :)
Download sample
You can download complete sample from mediafire.
Unzip package
unzip pbsb.zip # can also do via graphical interface if you prefer.
What's inside zip
./app.js
const PORT = 3000;
const HOST = 'localhost';
var express = require('express');
var app = module.exports = express.createServer();
app.use(express.staticProvider(__dirname + '/public'));
const redis = require('redis');
const client = redis.createClient();
const io = require('socket.io');
if (!module.parent) {
app.listen(PORT, HOST);
console.log("Express server listening on port %d", app.address().port)
const socket = io.listen(app);
socket.on('connection', function(client) {
const subscribe = redis.createClient();
subscribe.subscribe('pubsub'); // listen to messages from channel pubsub
subscribe.on("message", function(channel, message) {
client.send(message);
});
client.on('message', function(msg) {
});
client.on('disconnect', function() {
subscribe.quit();
});
});
}
./public/index.html
<html>
<head>
<title>PubSub</title>
<script src="/socket.io/socket.io.js"></script>
<script src="/javascripts/jquery-1.4.3.min.js"></script>
</head>
<body>
<div id="content"></div>
<script>
$(document).ready(function() {
var socket = new io.Socket('localhost', {port: 3000, rememberTransport: false/*, transports: ['xhr-polling']*/});
var content = $('#content');
socket.on('connect', function() {
});
socket.on('message', function(message){
content.prepend(message + '<br />');
}) ;
socket.on('disconnect', function() {
console.log('disconnected');
content.html("<b>Disconnected!</b>");
});
socket.connect();
});
</script>
</body>
</html>
Start server
cd pbsb
node app.js
Start browser
Best if you start google chrome(because of websockets support, but not necessary). Visit http://localhost:3000 to see sample(in the beginning you don't see anything but PubSub as title).
But on publish to channel pubsub you should see a message. Below we publish "Hello world!" to the browser.
From ./redis-cli
publish pubsub "Hello world!"
here's a simplified example without as many dependencies.
You do still need to npm install hiredis redis
The node JavaScript:
var redis = require("redis"),
client = redis.createClient();
client.subscribe("pubsub");
client.on("message", function(channel, message){
console.log(channel + ": " + message);
});
...put that in a pubsub.js file and run node pubsub.js
in redis-cli:
redis> publish pubsub "Hello Wonky!"
(integer) 1
which should display: pubsub: Hello Wonky! in the terminal running node!
Congrats!
Additional 4/23/2013: I also want to make note that when a client subscribes to a pub/sub channel it goes into subscriber mode and is limited to subscriber commands. You'll just need to create additional instances of redis clients. client1 = redis.createClient(), client2 = redis.createClient() so one can be in subscriber mode and the other can issue regular DB commands.
Complete Redis Pub/Sub Example (Real-time Chat using Hapi.js & Socket.io)
We were trying to understand Redis Publish/Subscribe ("Pub/Sub") and all the existing examples were either outdated, too simple or had no tests.
So we wrote a Complete Real-time Chat using Hapi.js + Socket.io + Redis Pub/Sub Example with End-to-End Tests!
https://github.com/dwyl/hapi-socketio-redis-chat-example
The Pub/Sub component is only a few lines of node.js code:
https://github.com/dwyl/hapi-socketio-redis-chat-example/blob/master/lib/chat.js#L33-L40
Rather than pasting it here (without any context) we encourage you to checkout/try the example.
We built it using Hapi.js but the chat.js file is de-coupled from Hapi and can easily be used with a basic node.js http server or express (etc.)
Handle redis errors to stop nodejs from exiting. You can do this by writing;
subcribe.on("error", function(){
//Deal with error
})
I think you get the exception because you are using the same client which is subscribed to publish messages. Create a separate client for publishing messages and that could solve your problem.
Check out acani-node on GitHub, especially the file acani-node-server.js. If these links are broken, look for acani-chat-server among acani's GitHub public repositories.
If you want to get this working with socket.io 0.7 AND an external webserver you need to change (besides the staticProvider -> static issue):
a) provide the domain name instead of localhost (i.e. var socket = io.connect('http://my.domain.com:3000'); ) in the index.html
b) change HOST in app.js (i.e. const HOST = 'my.domain.com'; )
c) and add sockets in line 37 of app.js (i.e. 'socket.sockets.on('connection', function(client) { …' )
Update to the code:
staticProvider
now renamed to
static
see migration guide
according to #alex solution. if you have an error like this one as per #tyler mention:
node.js:134
throw e; // process.nextTick error, or 'error'
event on first tick ^ Error: Redis connection to 127.0.0.1:6379 failed - ECONNREFUSED, Connection refused at Socket.
then you need to install Redis first. check this out:
http://redis.io/download