socketio expressjs difference between two implementation - node.js

Is there any difference between this implementation:
this.app = express();
this.httpServer = http.createServer(this.app);
this.io = socket.listen(this.httpServer);
And this one:
this.app = express();
this.server = http.createServer(this.app);
this.io = socket(this.server);

Nopers, the second is a shorthand. :)
The first is provided in the event that you want to import/export the function from your express architecture
It seems like your other question was posted after this, is this still relevant?
Ok let's see what I've done that worked. I have seperated my sockets into a config file because my app.js was getting cluttered.
app.use(express.static(path.join(__dirname, '/')));
app.use(express.static(path.join(__dirname, '/node_modules/')));
var clients = {};
var server = http.createServer(app);
var io = require('socket.io')(server);
require('./config/app.socket.js')(io);
server.listen(8001);
io.set("origins", "*:*");
So, I cut out the middleman and pass the server directly to the socket.io import. then, I pass the reference to that io server to my app.socket.js file and listen to the server on port 8001
Here is my app.socket.js initialization
module.exports = function(io){
var clients = {};
var sockets;
io.on('connection', function (socket) {
sockets = socket;
socket.on(//your socket function)
}

Related

nodejs socket.io express handshake error

I try to create a real time app by socket.io.
Server side:
var express = require('express');
var io = require('socket.io');
var engine = require('ejs-locals');
var app = express()
, server = require('http').createServer(app)
, io = io.listen(server);
app.engine('ejs', engine);
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.redirect('/login')
});
app.use(express.static(__dirname + '/public'));
app.listen(3001);
io.sockets.on('connection', function (socket) {
console.log('Client connected...');
socket.on('send_login_data', function (data) {
console.log(data);
});
});
Client side:
var socket = io.connect('http://localhost:3001');
socket.on('connect_failed', function(){
console.log('Connection Failed');
});
socket.on('connecting', function () {
console.log('connecting...');
});
socket.on('connect', function () {
console.log('connected!');
});
I caught the next error:
GET http://localhost:3001/socket.io/1/?t=1447539302809 404 (Not Found)
As I understand, it's a handshake error.
How can I fix it?
Thanx.
First off, make absolutely sure there are no errors showing anywhere in case some module isn't installed properly.
Then, make sure you have the same version number of socket.io on client and server and that you have the server-side version installed on the server.
Then, I've seen folks have issue with this before, even when following the instructions on the socket.io web site and it's never been clear exactly what was wrong with that sequence. But, what I know is that this sequence will work:
var express = require('express');
var app = express();
var server = app.listen(3001);
var io = require('socket.io').listen(server);
See related issues: Where is my client side socket.io? and Node + Socket.io Connection issue
I don't know if this is causing the issue or not, but you are attempting to redefine the io variable when it has already been declared in this:
var io = require('socket.io');
var app = express()
, server = require('http').createServer(app)
, io = io.listen(server);
The second reference to io = io.listen(server) is essentially this:
var io = require('socket.io');
var app = express();
var server = require('http').createServer(app);
var io = io.listen(server);
Which is not correct Javascript. Again, may not be causing your issue, but it is not technically proper Javascript.

express and socket.io - declaration and starting server

I've never understood how the below codes are equivalent:
Code 1:
var app = require("express")();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
...
io.use(...);
...
server.listen(3000, function(){});
Code 2:
var app = require("express")().listen(3000);
var io = require("socket.io")(app);
...
io.use(...);
Code 3:
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
...
io.use(...);
...
server.listen(3000, function(){});
Can you please help me understand what is happening here ? And is one approach preferable over the other (and under what circumstances) ? Thanks.
The snippets are not equivalent. Some are from older versions of express and socket.io and some are more recent. I would use a modified example from the socket.io documentation.
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
/* Setup Express */
app.get('/', function (req, res) {
...
});
/* Setup Socket.io */
io.on('connection', function (socket) {
...
});
server.listen(3000);
Express now just exposes a handler function app which you pass to an http server. Socket.io expects you to pass it an http server for it to plug into.

How to access io instance in a third part file?

I need to access my socket.io instance in some differents files, how do you make it works?
Here is what i tried:
main.js
var app = express();
var sockets = require('./sockets');
sockets.listen(app)
sockets.js
var io = require('socket.io');
exports.listen = function(app) {
io = io.listen(app);
//...
}
exports.io = io;
SomeClass.js
var io = require('./sockets').io;
var SomeClass = function() {
var Clients = io.sockets.clients('room');
//io is undefined...
}
exports.SomeClass = SomeClass;
In your file, io.sockets is undefined because you are starting your server incorrectly. Socket.IO expects a HTTP server instance, and you are instead passing an Express instance. You are also trying to change a variable after it has been exported, and that does not work. This is what you should be doing:
var http = require('http');
var express = require('express');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server):
server.listen(80);
If you still wanted to split this up into files, you would have to put your Socket.IO instance in your main application, and pass it to other modules when requiring them.

Need for module.parent in the following node.js code

const PORT = 3000;
const HOST = 'localhost';
var express = require('express'),
http = require('http'),
server = http.createServer(app);
var app = express();
const redis = require('redis');
const client = redis.createClient();
const io = require('socket.io');
if (!module.parent) {
server.listen(PORT, HOST);
const socket = io.listen(server);
socket.on('connection', function(client) {
const subscribe = redis.createClient()
subscribe.subscribe('realtime');
...
...
});
});
}
I stumbled upon this piece of code in one of the sites , In the above code I want to know the reason why the condition (!module.parent) is used ??? Whats the need for using it ??
If there is no module.parent it probably means that the module is being run on its own rather than being used in another program. If the !module.parent block is in a utility module I would guess that it is code for a test or developer tool. In a program that does stuff on it's own (e.g. a webserver), it would probably be the main entry point and the purpose of using it would be to make it possible to require components of that program without running the program.

How to connect Two Socket.io Node Application using Socket.io-client in Node js

In my application i need to connect two socket.io node applications.Using socket.io-client we can do like this.But i don't know how socket.io-client works and where to include that.
First Node Application
var express = require('express')
, http = require('http');
var app = express();
app.use(function (req, res) {
app.use(express.static(__dirname + '/public'));
});
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);
io.sockets.on('connection',function(socket){
socket.on('eventFiredInClient',function(data){
socket.emit('secondNodeAppln',data);// i need to get this event in my 2nd node application how can i do this by using socket.io-client
});
});
Second Node Application
var express=require('express');
var http=require('http');
var app=express();
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
var server = http.createServer(app);
var serverAddress = '127.0.0.1';
var serverPort = 3000; //first node appln port
var clientio = require('socket.io-client');
var socket = clientio.connect(serverAddress , { port: serverPort });
socket.on('connect', function(){
console.log('connected');
});
socket.on('disconnect', function(){
console.log('disconnected');
});
var io = require('socket.io').listen(server);
server.listen(6509);
//here i need to get the 'secondNodeAppln' event raised in first node application.How can i do this.
You need to create a socket.io client in your first app:
var io = require('socket.io').listen(server); // this is the socket.io server
var clientio = require('socket.io-client'); // this is the socket.io client
var client = clientio.connect(...); // connect to second app
io.sockets.on('connection',function(socket) {
socket.on('eventFiredInClient',function(data) {
client.emit('secondNodeAppln', data); // send it to your second app
});
});
And in your second app, just listen for those events:
io.sockets.on('connection', function (socket) {
socket.on('secondNodeAppln', function(data) {
...
});
});
There's a bit of a race condition because the code above doesn't wait for a connect event on the client socket before passing events to it.
EDIT see this gist for a standalone demo. Save the three files to a directory, start the servers:
node serverserver &
node clientserver
And open http://localhost:3012 in your browser.

Resources