Edit Page

io.socket.on()

Start listening for server-sent events from Sails with the specified eventIdentity. Will trigger the provided callback function when a matching event is received.

io.socket.on(eventIdentity, function (msg) {
  // ...
});

Usage

Argument Type Details
1 eventIdentity The unique identity of a server-sent event, e.g. "recipe"
2 handlerFn Will be called when the server emits a message to this socket.
Event handler
Argument Type Details
1 msg The message broadcasted from the Sails server.

Note that the event handler will NEVER be called until one of your back-end controllers, models, services, etc. sends a message to this socket. Typically that is achieved one of the following ways:

Resourceful Pubsub Methods
  • server publishes a message about a record to which this socket is subscribed (see Model.publishUpdate(), Model.publishDestroy(), and Model.subscribe())
  • server publishes a message informing all permitted watcher sockets that a new record has been created in the model with the same identity as eventIdentity (see Model.publishCreate(http://sailsjs.com/documentation/reference/web-sockets/resourceful-pub-sub/publish-create) and Model.watch())
Low-Level Socket Methods (sails.sockets)
  • server emits a message to all known sockets (see sails.sockets.blast())
  • server emits a message directly to this socket (io.socket) using its unique id (see sails.sockets.emit())
  • server broadcasts to a room in which this socket (io.socket) has been allowed to join (remember that a socket only stays subscribed as long as it is connected-- i.e. as long as the browser tab is open)

Example

Listen for new orders and updates to existing orders:

io.socket.on('order', function onServerSentEvent (msg) {
  // msg => {...whatever the server broadcasted...}
});
Another example, this time using Angular:

Note that this Angular example assumes the backend calls publishCreate() at some point.

angular.module('cafeteria').controller('CheckoutCtrl', function ($scope) {

  $scope.orders = $scope.orders || [];

  if (!io.socket.alreadyListeningToOrders) {
    io.socket.alreadyListeningToOrders = true;
    io.socket.on('order', function onServerSentEvent (msg) {

      // Let's see what the server has to say...
      switch(msg.verb) {

        case 'created':
          $scope.orders.push(msg.data); // (add the new order to the DOM)
          $scope.$apply();              // (re-render)
          break;

        default: return; // ignore any unrecognized messages
      }
    });
  }
});

Handle Socket 'Connect' and 'Disconnect' events

If a socket's connection to the server was interrupted-- perhaps because the server was restarted, or the client had some kind of network issue-- it is possible to handle connect and disconnect events and manually reconnect the socket again. sails.io.js does this for you automatically, but you can also bind your own handlers. While this is not recommended for 99% of apps, usage is documented below for completeness:

io.socket.on('connect', function(){
      io.socket.get('/messages');
      io.socket.get('/notifications/subscribe/statusUpdates');
  });

  io.socket.on('disconnect', function(){
      console.log('Lost connection to server');
  });

Notes

  • When listening for resourceful pubsub calls, the eventIdentity is the same as the identity of the calling model (e.g. if you have a model "UserComment", the identity is "usercomment".)
  • For context-- these types of server-sent events are sometimes referred to as "comet") messages.

Is something missing?

If you notice something we've missed or could be improved on, please follow this link and submit a pull request to the sails-docs repo. Once we merge it, the changes will be reflected on the website the next time it is deployed.

Sails logo
  • Home
  • Get started
  • Support
  • Documentation
  • Documentation

For a better experience on sailsjs.com, update your browser.

Documentation

Reference Concepts App structure | Upgrading Contribution guide | Tutorials More

Reference

  • Application
    • Events
    • Lifecycle
    • sails.getRouteFor()
    • sails.getUrlFor()
    • sails.lift()
    • sails.load()
    • sails.log()
    • sails.lower()
    • sails.request()
    • sails.getBaseUrl()
  • Blueprint API
    • add to
    • create
    • destroy
    • find one
    • find where
    • populate where
    • remove from
    • update
  • Command Line Interface
    • sails console
    • sails debug
    • sails generate
    • sails lift
    • sails new
    • sails version
  • Configuration
    • sails.config.*
    • sails.config.blueprints
    • sails.config.bootstrap()
    • sails.config.connections
    • sails.config.cors
    • sails.config.csrf
    • sails.config.globals
    • sails.config.http
    • sails.config.i18n
    • sails.config.log
    • sails.config.models
    • sails.config.policies
    • sails.config.routes
    • sails.config.session
    • sails.config.sockets
    • sails.config.views
  • Request (`req`)
    • req.accepted
    • req.acceptedCharsets
    • req.acceptedLanguages
    • req.body
    • req.cookies
    • req.fresh
    • req.headers
    • req.host
    • req.ip
    • req.ips
    • req.isSocket
    • req.method
    • req.options
      • req.options.values
      • req.options.where
    • req.originalUrl
    • req.params
    • req.path
    • req.protocol
    • req.query
    • req.secure
    • req.signedCookies
    • req.socket
    • req.subdomains
    • req.url
    • req.wantsJSON
    • req.xhr
    • req.accepts()
    • req.acceptsCharset()
    • req.acceptsLanguage()
    • req.allParams()
    • req.file()
    • req.get()
    • req.is()
    • req.param()
  • Response (`res`)
    • res.attachment()
    • res.badRequest()
    • res.clearCookie()
    • res.cookie()
    • res.created()
    • res.forbidden()
    • res.get()
    • res.json()
    • res.jsonp()
    • res.location()
    • res.negotiate()
    • res.notFound()
    • res.ok()
    • res.redirect()
    • res.send()
    • res.serverError()
    • res.set()
    • res.status()
    • res.type()
    • res.view()
  • Waterline (ORM)
    • Models
      • .count()
      • .create()
      • .destroy()
      • .find()
      • .findOne()
      • .findOrCreate()
      • .native()
      • .query()
      • .stream()
      • .update()
    • Populated Values
      • .add()
      • .remove()
    • Queries
      • .exec()
      • .limit()
      • .populate()
      • .skip()
      • .sort()
      • .where()
    • Records
      • .save()
      • .toJSON()
      • .toObject()
  • WebSockets
    • Resourceful PubSub
      • .message()
      • .publishAdd()
      • .publishCreate()
      • .publishDestroy()
      • .publishRemove()
      • .publishUpdate()
      • .subscribe()
      • .unsubscribe()
      • .unwatch()
      • .watch()
      • .subscribers()
    • sails.sockets
      • .addRoomMembersToRooms()
      • .blast()
      • .broadcast()
      • .getId()
      • .join()
      • .leave()
      • .leaveAll()
      • .removeRoomMembersFromRooms()
      • sails.sockets.emit()
      • sails.sockets.id()
      • sails.sockets.rooms()
      • sails.sockets.socketRooms()
      • sails.sockets.subscribers()
    • Socket Client
      • io.sails
      • io.socket
      • SailsSocket
        • Methods
        • Properties
      • io.socket.delete()
      • io.socket.get()
      • io.socket.off()
      • io.socket.on()
      • io.socket.post()
      • io.socket.put()
      • io.socket.request()

Built with Love

The Sails framework is maintained by a web & mobile studio in Austin, TX, with the help of our contributors. We created Sails in 2012 to assist us on Node.js projects. Naturally we open-sourced it. We hope it makes your life a little bit easier!

Sails:
  • What is Sails?
  • Treeline IDE
  • Contribute
  • Logos/artwork
About:
  • The Sails Company
  • Security
  • News
  • Legal
Help:
  • Get started
  • Documentation
  • Docs
  • Enterprise
  • Hire us

© 2012-2018 The Sails Company. 
The Sails framework is free and open-source under the MIT License.