mercoledì 16 aprile 2014

Node.js simple chat application > Node.js javascript

Following this nice tutorial (I'm a naive myself with node.js), I ended up having some problem due to the changes beetween express 2.x and express 3.x. I won't go into details, you can find anything you need to know in the previously linked article, here the modified and working code for current express, and jade implementation.

var http = require('http');
var express = require('express'); //package che ci semplifica la parte server-side
var app = express(); //this is different from old method .createServer(), it returns a javascript function
var jade = require('jade'); //tamplate gestore
var io = require('');
var server = http.createServer(app);

io = io.listen(server); //this return the new object we want to listen to 

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set("view options", {layout: false});

app.use(express.static(__dirname + '/public')); //no need to use .configure

app.get('/', function(req, res){
//app.listen(3000); //express ascolterà questa porta

//connection even lanciato quando un client prova a collegarsi al server
// crea una nuova socket (utilizzata poi per scambiare messaggi)
io.sockets.on('connection', function(socket){
 socket.on('setPseudo', function(data){
  socket.set('pseudo', data); //il nickname? lo pseudonimo per quella socket?
 socket.on('message', function (message) {
    socket.get('pseudo', function (error, name) {
        var data = { 'message' : message, pseudo : name };
        socket.broadcast.emit('message', data);
        console.log("user " + name + " send this : " + message);

//The nice thing about is that we don't have to worry about handling client disconnections.
//When it disconnects, will no longer receive responses to "heartbeat" messages
//and will deactivate the session associated with the client.
//If it was just a temporary disconnection, the client will reconnect and continue with the session.

Also in home.jade, the doctype 5 line is deprecated, use doctype html instead.
If you wish to know more about node.js, please read the referred article by .

Nessun commento:

Posta un commento