Forse questo potrebbe aiutare anche te. Avevo qualche problema ad avvolgere la testa su come funzionava socket.io, quindi ho provato a riassumere un esempio il più possibile.
Ho adattato questo esempio dall'esempio pubblicato qui: http://socket.io/get-started/chat/
Per prima cosa, inizia in una directory vuota e crea un file molto semplice chiamato package.json Inserisci quanto segue.
{
"dependencies": {}
}
Successivamente, sulla riga di comando, usa npm per installare le dipendenze di cui abbiamo bisogno per questo esempio
$ npm install --save express socket.io
Questo potrebbe richiedere alcuni minuti a seconda della velocità della tua connessione di rete / CPU / ecc. Per verificare che tutto sia andato come previsto, puoi guardare di nuovo il file package.json .
$ cat package.json
{
"dependencies": {
"express": "~4.9.8",
"socket.io": "~1.1.0"
}
}
Crea un file chiamato server.js Questo sarà ovviamente il nostro server gestito da nodo. Inserisci il seguente codice in esso:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){
console.log('listening on *:3001');
});
//for testing, we're just going to send data to the client every second
setInterval( function() {
/*
our message we want to send to the client: in this case it's just a random
number that we generate on the server
*/
var msg = Math.random();
io.emit('message', msg);
console.log (msg);
}, 1000);
Crea l'ultimo file chiamato index.html e inserisci il codice seguente.
<html>
<head></head>
<body>
<div id="message"></div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('message', function(msg){
console.log(msg);
document.getElementById("message").innerHTML = msg;
});
</script>
</body>
</html>
Ora puoi testare questo esempio molto semplice e vedere un output simile al seguente:
$ node server.js
listening on *:3001
0.9575486415997148
0.7801907607354224
0.665313188219443
0.8101786421611905
0.890920243691653
Se apri un browser web e lo punti al nome host su cui stai eseguendo il processo del nodo, dovresti vedere gli stessi numeri apparire nel tuo browser, insieme a qualsiasi altro browser connesso che guarda la stessa pagina.