Socket.io with two node.js servers? - javascript

I am a confused how to use socket.io so that two node servers can emit events between each other.
Server.js localhost:9200
io.sockets.on('connection', function(socket) {
socket.on('messageFromClient', function(data) {
socket.broadcast.to(data.chatRoom).emit('messageFromServer', data);
});
});
This socket connection listens to the server like so
var appPort = 9200;
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
// Launch server
server.listen(appPort);
I have a website being served by node.js... Server.js localhost:3000: I need this to be able to receive and emit events from localhost:9200
How do I setup server.js for localhost:3000?

I figured this out, it's really quite simple. There can be two node servers, but only one server needs to use socket.io and handle the events. All you need to do to connect is share the client side script via CORS, I wanted to avoid CORS, but you only need to share the socket.io script over CORS and nothing else, so it's not so bad.
First thing needed is to allow your other domain to access the script via CORS.
// requires cors module I think (var cors = require('cors');)
var corsOptions = {
origin: 'http://localhost:3100',
credentials: true
};
Then secondly, it's important client side to use io.connect I am not sure if that was depreciated or something but none of the modern docs mention this.
// What worked for me
var socket = io.connect('http://localhost:3100');
// Docs say
var socket = io('http://localhost:3100'); // ?? I am not sure why but io.connect worked for me.

Related

jQuery callback function not working for cross domain

I'm using
nodejs in backend at localhost:3000
and
http Apache server at localhost:8080
$.post("http://localhost:3000", {data:"data"}, function(){alert("hurrah");});
// that one not working
$.get("http://localhost:3000", {data:"data"}, function(){alert("hurrah");});
// is working, but callback function not working
Have you checked out Cors for NodeJS?
Cross Domain requests may be blocked to your web server and if you're running NodeJS, you can add Cors(), configure the content you wish to accept (or accept all for the sake of debugging / time at the moment).
Depending on your NodeJS configuration you can set this up by including it at the top of your main class.
A default configuration, using Express might look something like this... (note this accepts all content!)
var express = require('express');
var app = express();
var cors = require('cors');
app.use(cors());
app.listen(8080, () => {
console.log('Listening on 8080');
});

Correct ports for node server-client application with Heroku

Well, I'm near to finish my starting app... but port issue is hard...
My server.js has this
const port = process.env.PORT;
const express = require('express'), http = require('http');
const app = express();
const server = app.listen(port);
const io = require('socket.io').listen(server);
And now the issue. What should I do in the client?
var socket = io.connect('https://myweb.herokuapp.com:3000/');
var socket = io.connect('https://localhost:3000/');
I tried those two... the second one, localhost (but with 8080) works in local... but displays the error
GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=M9zP_yz net::ERR_CONNECTION_RESET
I read that the client is picking the CLIENT PC localhost and that fails, that has to pick the SERVER PC route... so I tried the first option, the application URL... because I suppose I don't have to use the server IP (I also don't have it). But nothing works...
Try using port 80, that should be the default port accessible outside heroku dynos: https://myweb.herokuapp.com:80/. If it does not work, try connecting without the port. Use the URL only: https://myweb.herokuapp.com

Given a server on Node. js, How do I listen to the calls sent to the server from WebSocket?

When I run the server, I wanted to be able to listen to the messages coming in to the server. However, the program/server is only set up to receive the calls without any notice
server.js
var express = require("express"),
program = require("program"),
app = express.createServer();
app.use(express["static"](__dirname + "/../"));
app.listen(5000);
//app.server to clients
program.init({
oscPort: xxxx,
oscHost: "xxx.xxx.xxx"
socketPort: app
});
You should add socket server because HTTP and Socket it's different protocols. There is a bunch of WebSocket servers like ws, socket.io so you could pick the one which is most suitable in your case. Here is an example how to use Socket.io with Express.

Issues with using Socket.io

I am trying to use socket.io for the first time, Im using it with a MEAN Stack. I have set it up the following way.
Server.js
var express = require('express');
var app = express(); // create our app w/ express
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.listen(port);
io.on('connection', function(socket) {
socket.emit('message', {
'message': 'hello world'
});
});
HTML File
<script>
var socket = io.connect();
socket.on('message', function(data) {
console.log(data.message);
});
</script>
I couldn't find the socket.io.js file so I searched for a CDN for the script. I used the following.
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.6/socket.io.js"></script>
I tried downloading the socket.io.js from their website but the website seems to be down. I can access it, I get the 502 BAD GATEWAY error (http://socket.io)
When I load my HTML page after setting everything up as shown above I get the following error in the console.
Any help will be greatly appreciated!
UPDATE:
The socket.io server will perform some magic to provide that file when you retrieve it like this:
<script src="/socket.io/socket.io.js"></script>
EDIT: ah, I see the problem: your Express setup is incorrect.
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.listen(port);
You're attaching socket.io to a server created by http.createServer, but with app.listen() you're actually creating a new server, one that socket.io isn't attached to.
You can make the setup a bit simpler:
var express = require('express');
var app = express();
var server = app.listen(port);
var io = require('socket.io')(server);
No need to use http.
As of now, socket.io website is still down. If you don't have the file in your server, it does not help using /socket.io/ because this points to a route on your server and that route doesn't seem to exist on your app. With this config, you need to be serving the .js file statically from your server - but I don't see that on your server code.
When you try the CDN, make sure the file is being loaded.

Can I configure expressjs to serve some pages over http and others over https?

Based on the response to this question:
How do I configure nodejs/expressjs to serve pages over https?
I've been trying to set up the equivalent of:
var express = require('express');
var fs = require("fs");
var crypto = require('crypto');
var app = express.createServer();
var appSecure = express.createServer();
var privateKey = fs.readFileSync('privatekey.pem').toString();
var certificate = fs.readFileSync('certificate.pem').toString();
var credentials = crypto.createCredentials({key: privateKey, cert: certificate});
appSecure.setSecure(credentials);
app.get('/secretStuff', function(req,res) {
//redirect to https
}
appSecure.get('/secretStuff', function(req, res) {
//show you the secret stuff
}
Is this something that's doable with the current release of expressjs and node 2.4?
Yes, this can be done and it looks like you already have most of what you need. Just send the redirect in your app.get handler
app.get('/secretStuff', function(req,res) {
res.redirect('https://' + req.header('Host') + req.url);
}
Also make sure you do something like app.listen(80) and appSecure.listen(443) to actually start the servers on the appropriate port. Otherwise be sure to construct the HTTPS URL with the correct port. For production, this thing is typically handled outside of your app server (node.js) with a reverse proxy like nginx. It is trivial to do this in nginx which will let your node.js process run as non-root and remove the need to have clients directly connecting to node.js, which is not as battle-hardened as nginx for serving live internect TCP connections (I'm paraphrasing Ryan Dahl himself here).
You can only serve a web page over the connection that the request came in. If the request did not come in over https, you can't send the response that way.
So, first you have to be listening for both http and https requests. If a request comes in over http that you want to answer over a secure connection, do not do any processing but immediately redirect it to an https url. Then when the client reissues the request, process as normally.
If the framework uses JSGI then you can probably use the redirect module from Jack otherwise you will have to do it yourself. The details are at the link, i.e. response code 301 and Location: header with the https URL.

Categories