Git Product home page Git Product logo

kledal / ember-websockets Goto Github PK

View Code? Open in Web Editor NEW

This project forked from thoov/ember-websockets

0.0 2.0 0.0 295 KB

EmberJS WebSockets and Socket.IO addon for Ember-CLI apps. This addon aims to be a simple and easy way to integrate with any websocket supported backend. It has been designed to be minimalistic, flexible, and lightweight instead of forcing conventions on the developer.

License: MIT License

JavaScript 93.61% HTML 5.79% CSS 0.60%

ember-websockets's Introduction

EmberJS WebSockets Addon

This addon aims to be a simple and easy way to integrate with any websocket or socket.io backend. It has been designed to be minimalistic, flexible, and lightweight instead of forcing certain conventions on the developer. This addon is compatible with EmberJS 2.0!

http://www.programwitherik.com/getting-started-with-web-sockets-and-ember/

Build Status Code Climate Ember Observer Score npm version

Installation

ember install ember-websockets

Simple example of using it in your app

import Ember from 'ember';

export default Ember.Controller.extend({

  /*
  * 1) First step you need to do is inject the websocket service into your object. You
  * can inject the service into component, controllers, object, mixins, routes, and views.
  */
  socketService: Ember.inject.service('websockets'),

  init: function() {
    this._super.apply(this, arguments);

    /*
    * 2) The next step you need to do is to create your actual websocket. Calling socketFor
    * will retrieve a cached websocket if one exists or in this case it
    * will create a new one for us.
    */
    var socket = this.get('socketService').socketFor('ws://localhost:7000/');

    /*
    * 3) The final step is to define your event handlers. All event handlers
    * are added via the `on` method and take 3 arguments: event name, callback
    * function, and the context in which to invoke the callback. All 3 arguments
    * are required.
    */
    socket.on('open', this.myOpenHandler, this);
    socket.on('message', this.myMessageHandler, this);
    socket.on('close', function(event) {
      // anonymous functions work as well
    }, this);
  },

  myOpenHandler: function(event) {
    console.log('On open event has been called: ' + event);
  },

  myMessageHandler: function(event) {
    console.log('Message: ' + event.data);
  },

  actions: {
    sendButtonPressed: function() {
      /*
      * If you need to retrieve your websocket from another function or method you can simply
      * get the cached version at no penalty
      */
      var socket = this.get('socketService').socketFor('ws://localhost:7000/');
      socket.send('Hello Websocket World');
    }
  }
});

Sending messages to the server

var socket = this.get('socketService').socketFor('ws://localhost:7000/');
socket.send('Hello Websocket World', true);

The send method takes 2 arguments. A message which is passed into the native websockets send method and an optional stringify boolean. This boolean, if set to true, will do a JSON.stringify to the message before passing it to the websocket send method. If you are sending strings it is recommended to pass true.

Reconnecting

import Ember from 'ember';

export default Ember.Controller.extend({
  socketService: Ember.inject.service('websockets'),

  init: function() {
    this._super.apply(this, arguments);

    var socket = this.get('socketService').socketFor('ws://localhost:7000/');

    socket.on('open', function(event) {
      console.log('This will be called');
    }, this);

    socket.on('close', function(event) {
      Ember.run.later(this, function() {
        /*
        * This will remove the old socket and try and connect to a new one on the same url.
        * NOTE: that this does not need to be in a Ember.run.later this is just an example on
        * how to reconnect every second.
        */
        socket.reconnect();
      }, 1000);
    }, this);
  }
});

Closing the connection

import Ember from 'ember';

export default Ember.Controller.extend({
  socketService: Ember.inject.service('websockets'),

  /*
  * To close a websocket connection simply call the closeSocketFor method. NOTE: it is good
  * practice to close any connections after you are no longer in need of it. A good
  * place for this clean up is in the willDestroy method of the object.
  */
  willDestroy() {
    this.get('socketService').closeSocketFor('ws://localhost:7000/');
  }
});

Multiple Websockets

import Ember from 'ember';

export default Ember.Controller.extend({
  socketService: Ember.inject.service('websockets'),

  init: function() {
    this._super.apply(this, arguments);

    var socketOne = this.get('socketService').socketFor('ws://localhost:7000/');
    var socketTwo = this.get('socketService').socketFor('ws://localhost:7001/');

    socketOne.on('open', function(event) {
      console.log('Hello from socket one');
    }, this);

    socketTwo.on('open', function(event) {
      console.log('Hello from socket two');
    }, this);
  }
});

Multiple Event Handlers

import Ember from 'ember';

export default Ember.Controller.extend({
  socketService: Ember.inject.service('websockets'),

  init: function() {
    this._super.apply(this, arguments);

    var socket = this.get('socketService').socketFor('ws://localhost:7000/');

    socket.on('open', function(event) {
      console.log('This will be called');
    }, this);

    socket.on('open', function(event) {
      console.log('This will also be called');
    }, this);
  }
});

Socket.IO Support

First run the socket.io generator via:

ember g socket-io
import Ember from 'ember';

export default Ember.Controller.extend({

  /*
  * 1) First step you need to do is inject the socketio service into your object.
  */
  socketIOService: Ember.inject.service('socket-io'),

  init: function() {
    this._super.apply(this, arguments);

    /*
    * 2) The next step you need to do is to create your actual socketIO.
    */
    var socket = this.get('socketIOService').socketFor('http://localhost:7000/');

    /*
    * 3) Define any event handlers
    */
    socket.on('connect', function() {
      /*
      * There are 2 ways to send messages to the server: send and emit
      */
      socket.send('Hello World');
      socket.emit('Hello server')
    }, this);

    /*
    * 4) It is also possible to set event handlers on specific events
    */
    socket.on('message', this.onMessage, this);

    socket.on('myCustomNamespace', function() {
      socket.emit('anotherNamespace', 'some data');
    }, this);
  },

  onMessage: function(data) {
    // This is executed within the ember run loop
  }
});

Please visit: socket.io docs for more details on ember-websocket + socket.io

Detailed explanations of the APIs

SocketFor

Example:

var socket = this.get('socketService').socketFor('ws://localhost:7000/', ['myOptionalProtocol']);

socketFor takes two arguments: a url, a protocol array (optional), and returns a socket instance from its cache or a new websocket connection if one was not found.

On

Example:

var socket = this.get('socketService').socketFor('ws://localhost:7000/');

socket.on('open', this.myOpenFunction, this);

on takes 3 arguments: event type, callback function, and context. Event type can be one of the following: 'open', 'message', 'close', and 'error'. Callback function will be invoked when one of the event types occurs. Context is used to set the context of the callback function and also to remove the listeners when the context gets destroyed.

Off

Example:

var socket = this.get('socketService').socketFor('ws://localhost:7000/');

socket.on('open', this.myOpenFunction, this);
socket.off('open', this.myOpenFunction);

off takes 2 arguments: event type, callback function. Event type can be one of the following: 'open', 'message', 'close', and 'error'. The callback will be removed from the event pool and will no longer be invoked.

CloseSocketFor

Example:

var socket = this.get('socketService').socketFor('ws://localhost:7000/');

this.get('socketService').closeSocketFor('ws://localhost:7000/');

closeSocketFor takes a single argument, a url, and closes the websocket connection. It will also remove it from the cache. In normal cases you would not have to call this method.

Reconnect

Example:

socket.on('close', function(event) {
  socket.reconnect();
});

reconnect takes no arguments. It will attempt to create a new websocket connect using the previous url. If the connect is not successful the close event will be triggered.

Deprecations

Before v1.0.0 there was a websocket mixin that you would add to your router and you would define your event handlers via actions on the controller. If you still need the documentation for this approach it is here.

Live Example

The source code for the live example lives in ember-websockets/tests/dummy

Running tests

NOTE: To get the test to run in PhantomJS I created a mocking library found here: mocking library Note that it is still a work in progress.

Feedback or issues

If you have any feedback, encounter any bugs, or just have a question, please feel free to create a github issue or send me a tweet at @thoov.

FAQ

Recommended backend library/framework

Browser Support

Current support for browsers is fairly good with all modern browsers and most mobile browsers supporting websockets in their current and previously stable versions. It goes without saying that older versions of IE are not supported. For a more detailed break down

License

This addon falls under the MIT license

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.