Node.js: socket.io

De wikijoan
Salta a la navegació Salta a la cerca
$ npm install socket.io

Socket.io is Node.js module (like http is a module) which provides functionality to create web sockets to allow realtime communication between client and server. A socket is an end-point for communication and it’s represented by an IP address and Port No separated by colon. e.g. 127.0.0.1:8000.

A web socket means a socket for communication over the web.

Chat server

chat.js

var io     = require( 'socket.io' )
  , server = null;
 
//server = io.listen( 8000 ).set( 'log level', 1 );
server = io.listen( 8000 );
 
server.sockets.on( 'connection', function( socket ) {
    console.log ('hola...');
        socket.on( 'msg', function( data ) {
        socket.broadcast.emit( 'incMsg', data );
    });
});

chat.html

<input type="text" id="txt_msg" /> 
<input type="submit" id="btn_send" value="Send" /> 
<p><textarea id="txt_output" rows="20" cols="80" readonly="readonly"></textarea></p>

<script src="http://localhost:8000/socket.io/socket.io.js"></script>
<script>
document.addEventListener( 'DOMContentLoaded', function() {
    var socket = io.connect( 'http://localhost:8000' )
      , txt_msg = document.getElementById( 'txt_msg' ) 
      , btn_send = document.getElementById( 'btn_send' ) 
      , txt_output = document.getElementById( 'txt_output' ); 
 
    socket.on( 'incMsg', function( data ) { 
        if( data !== '' ) 
            txt_output.value += data + '\n'; 
    });
 
    document.addEventListener( 'keypress', function( e ) {
        if( e.keyCode === 13 ) { //if enter is pressed
            sendMsg();
        }
    });
 
    document.addEventListener( 'click', function() {
        sendMsg();
    });
 
    function sendMsg() {
        socket.emit( 'msg', txt_msg.value );
        txt_msg.value = '';
    }
});
</script>

Per tal de què funcioni s'han d'obrir com a mínim dues pestanyes en el navegador amb la url:

  • file:///home/joan/chat/chat.html

i veure com es pot establir la comunicació entre els dos.


creat per Joan Quintana Compte, desembre 2013