Socket. io usage

Source: Internet
Author: User
Tags emit socket connect
Document directory
  • Scenario
  • Socket. io
  • Actual use
  • Summary
Socket. io usage

2011-12-29

Scenario

The current project provides an online editor debugging function. You need to pass the debugging log information to the page in real time. Several people may open the editor to operate on the same project at the same time, the debugging information sent to these users is the same.

Generally, this scenario can be handled through the Comet server push and web socket. However, in nodejs, the socket. io module can be used to conveniently handle current affairs communication.

Socket. io

Socket. io is a project designed to implement cross-browser and cross-platform real-time applications. Automatic downgrade will be performed for different browser versions or different clients, and the appropriate implementation method (websocket, long pull...) will be selected to hide the implementation and only expose the unified interface. This allows applications to focus only on the business layer.

Nodejs Server Installation: npm install socket. io
After installation, you can use the require module:

  var sio = require('socket.io');

On the client, you can use

<script src="/socket.io/socket.io.js"></script>

Or use the socket. io CDN service.

<script src="http://cdn.socket.io/stable/socket.io.js"></script>

There are various usage introductions on its official website.

Actual use

This project is built on connect, so you need to use socket on connect. io. At the same time, because the file editing permission is limited, you also need. in io, session and other connection information are used to confirm the permission.

Let's take a look at the use of socket. io, server:

var io = require('socket.io').listen(80);io.sockets.on('connection', function (socket) {  socket.emit('news', { hello: 'world' });  socket.on('my other event', function (data) {    console.log(data);  });});

Browser:

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

When the server receives the connection event, the socket will carry a handshake information socket. handshake sent from the browser when the connection is established. We will print it out like this:

  { headers:    {      host: 'cnodejs.net:8080',     connection: 'keep-alive',     referer: 'http://cnodejs.net:8080/editor/pipe',     'user-agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.124 Safari/534.30',     accept: '*/*',     'accept-encoding': 'gzip,deflate,sdch',     'accept-language': 'zh-CN,zh;q=0.8',     'accept-charset': 'UTF-8,*;q=0.5',     cookie: 'NAEIDE_console_hide=0; lzstat_uv=7551240663017376909|2341473@2717849; lzstat_ss=2468024318_3_1325124834_2717849; connect.sid=z5sT8ER8SIzyknF6HYnIEdWz.l6oFdxYR24fSV85JIpLcpBabQtqDPB%2BUPm1DR1wqAEU; NAE_c_location=BOTTOM; NAE_c_display=1'      },  address: { address: '123.157.218.120', port: 60285 },  time: 'Thu Dec 29 2011 02:21:23 GMT+0800 (CST)',  query: { t: '1325096038995' },  url: '/socket.io/1/?t=1325096038995',  xdomain: false,  secure: undefined}

After the information on these browsers is obtained, it is easy to verify the permissions. Socket. io also provides

  io.set(authorization, callback);

To restrict the permissions of each connection.

Session and permission Verification

Session verification is an important part of permission verification. In handshake information, you can obtain the cookie information on the browser. According to the session mechanism of connect (express is the same, one of the cookies is connect. sid stores the session key in the server-side storage container. With this key, we can get the session value.

  var io = require('socket.io').listen(app);var ep = require('EventProxy.js').EventProxy;var parseCookie = require('connect').utils.parseCookie;io.set('authorization', function(data, accept){    var proxy = new ep();    //get sessionId from cookie & get session from sessionStore    var parse = function(){      if(data.headers.cookie){        //use parseCookie in connect.utils        data.cookie = parseCookie(data.headers.cookie);        data.sessionId = data.cookie['connect.sid'];        //getSession( by connect sessionStore.get)        SessionStore.get(data.sessionId, function(err, session){          if(err || !session){            proxy.unbind();            return accept(err.toString(), false);          }else{            data.session = session;            proxy.fire('session_got');          }        })      }else{        proxy.unbind();        return accept('No cookie transmitted.', false);      }    }    //get auth form database    var checkAuth = function(){      //get info in referer      data.app = getApp(data.headers.referer||'');      //check auth      check(data.session.user, data.app, function(err, result){        if(result){          accept(null, true);        }else{          accept(err?err.message:'permision denied.', false);        }      })    }    proxy.once('session_got', checkAuth);    parse();      })
Use socket. io to complete current affairs Communication

At this time, the handshake information of all verified connections already contains the app and session information. We classify these connections by app because all apps share the same connection, the received information will also be the same.

   io.sockets.on('connection', function(socket){  // some socket connect    var hs = socket.handshake;    //when socket connect, put this socket into room [hs.app]    socket.join(hs.app);        //some socket disconnect    socket.on('disconnect', function(){          });  });var proxy = new ep();//when get stdout data, send msg to sockets in this roomproxy.on('stdout', function(data){  io.sockets.in(data.room).send(data.log);})getData(data){  proxy.fire('stdout', data);}

At this time, as long as the output information is obtained, it will be transmitted to the page through socket. io, trigger the 'message' event of the page and render the page.

Disable debug information

When socket. io is enabled, information such as debug and heartbeat will be continuously played. in the production environment, we do not want to output such details.

  io.set('log level', 1); 

To disable the output of debugging information.

Summary

Socket. io is the best choice for nodejs to implement real-time web systems. It is especially compatible with node. js's event-driven features and can complete real-time systems without turning around.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.