• Blogs (9)
    • đŸ“± 236 - 992 - 3846

      📧 jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • Angular-fullstack + socket.io

    Blogs20142014-03-25


    I want to integrate socket.io into Angular-fullstack. I found some documents are Vague, so use my way to do the easily implementation:

    1. server side setting

    First npm install socket.io, then use it in server.js:

    // 1. install socket.io:
    $ npm install socket.io --save
    // 2. then in server.js, adding:
    var app = require('express')()
      , server = require('http').createServer(app)
      , io = require('socket.io').listen(server);
    
    server.listen(80);
    
    io.sockets.on('connection', function (socket) {
      socket.emit('news', { hello: 'world' });
      socket.on('my other event', function (data) {
        console.log(data);
      });
    });

    2. client side setting

    Similar as server-side, first bower install, then add it in angular’s ‘index.html’ entry point.

    $ bower install socket.io-client --save
    // then in index.html, adding:
    <script src='bower_components/socket.io-client/dist/socket.io.min.js'>
    
    // An alternative way to add client-side's socket.io.js is to
    // cp socket.io.js from node_modules/ to bower_components/, like this:
    $ cd node_modules/socket.io/
    $ find . -type f -name socket.io.js -exec mv {} ../../app/bower_components/ ;
    //then:
    <script src='bower_components/socket.io.js'>

    Any of them shoudl work. Basically the above 2 ways do the same thing: import socket.io.js client, then load into angularjs env.

    After that, adding client emit/on in ‘index.html’ to communicate with server side:

    <script type="text/javascript" src="bower_components/socket.io-client/dist/socket.io.js">
    <script>
        var socket = io.connect('http://localhost:9000');
        socket.on('news', function (data) {
            console.log(data);
            socket.emit('my other event', { my: 'data' });
        });
    </script>

    Now start the service, monitor socket.io’s behavors:

    1. $ grunt serve
    2. server-side: from command line, which is output of console.log()
    3. client-side: of cource the browser’s console

    The messages transferred btw server/client should display properly.