How to initialize an instance of socket.io? - node.js

I have discovered that there are at least 2 ways to go about doing this. The first way creates an HTTP server, although the 2nd way doesn't.
I am not able to find any concrete tutorial regarding this.
Case I
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(3000);
Case II
var app = require('express')();
var port = process.env.PORT || 3000;
var io = require('socket.io').listen(app.listen(port));
How are the two methods different? And why doesn't the second method require an HTTP server?

app.listen() creates the http server for you (a shortcut that express lets you use).
Here's the code for app.listen():
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
This Express code is here.

Related

Websocket With Socket.io & Angular

I want to create a websocket to add a communication between my angular app and my database. The app shall be able to save a question in a database & to notify the user when somebody answered.
Unfortunately I tried some tutorials which all don't work. I'm totally new to this because I use apache usually. So If you know a "working", very basic (beginner) tutorial, which doesn't require to install lots of additional things like yeoman etc. I would be glad.
In the current tutorial I get the error message:
You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.
My server.js:
var connect = require('connect'),
serveStatic = require('serve-static'),
socket = require('socket.io');
var server = connect();
server.use(serveStatic(__dirname+'/../client'));
server.listen(8080);
var io = socket.listen(server);
console.log("Server started and listen to http://127.0.0.1:8080");
without
var io = socket.listen(server);
it serves my static page.
This error is on my other approach:
has no method 'use'
My server.js
var connect = require('connect');
var http = require('http');
var serveStatic = require('serve-static');
var app = connect();
var server = http.createServer(app).use(serveStatic(__dirname+'/../client')).listen(3000);
var socket = require('socket.io');
var io = socket.listen(server);
As always if you struggle long the solution comes quick after posting. That one works for the beginning:
var connect = require('connect');
var http = require('http');
var app = connect();
var fs = require('fs');
var index = fs.readFileSync(__dirname+'/../client/index.html');
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end(index);
}).listen(3000);
var socket = require('socket.io');
var io = socket.listen(server);

http.createServer(app) v. http.Server(app)

On the socket.io web page, Get Started: Chat application, located here:
http://socket.io/get-started/chat/
there is this code:
var app = require('express')();
var http = require('http').Server(app);
which could be rewritten a little more clearly like this:
var express = require('express');
var http = require('http');
var app = express();
var server = http.Server(app);
The socket.io example uses http.Server() to create a server. Yet, the express docs for app.listen() show an example where the server is created using http.createServer(app):
app.listen()
Bind and listen for connections on the given host and port. This
method is identical to node's http.Server#listen().
var express = require('express');
var app = express();
app.listen(3000);
The app returned by express() is in fact a JavaScript Function,
designed to be passed to node's HTTP servers as a callback to handle
requests. This allows you to provide both HTTP and HTTPS versions of
your app with the same codebase easily, as the app does not inherit
from these (it is simply a callback):
var express = require('express');
var https = require('https');
var http = require('http');
var app = express();
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
The app.listen() method is a convenience method for the following (if
you wish to use HTTPS or provide both, use the technique above):
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
What's the difference between http.createServer(app) and http.Server(app)?? The http docs are no help.
There is no difference. http.createServer() only does one thing: it calls http.Server() internally and returns the resulting instance.

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.

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.

Connect2 and Socket.io

I'm trying to get connect and socket.io to work together nicely and simply. I have the following code on server side:
var connect = require('connect'),
io = require('socket.io');
var app = connect().use(connect.logger('dev'));
var sio = io.listen(app);
app.listen(8000);
when i open http://localhost:8000/socket.io/socket.io.js i'm get error:
Cannot GET /socket.io/socket.io.js
And Socket.IO not work, i'm trying copy file and load from another location, but socket.io requests do not reach the server
SOLUTION
if anyone comes to this issue, you need to wrap the connect/express app in a node http.Server. The app.listen() method is a convenience method for this and returns the server:
var io = require('socket.io');
var app = connect();
var server = app.listen(3000);
io.listen(server);
or the following is equivalent:
var io = require('socket.io');
var http = require('http');
var app = connect();
var server = http.createServer(app);
server.listen(3000);
io.listen(server);

Resources