Using Ember with Sockets

WebSockets make it possible to open a communication session with a server. Ember.js does not handle this natively. However, there are some easy-to-use add-ons that can be used to make this possible.

How to do it...

  1. In a new application, generate a new route and install the WebSockets add-on:
    $ ember install ember-websockets
    $ ember g component w-s
    $ ember g route ws
    

    This will install the component route and add-on that we need to begin.

  2. In the components template folder, edit the w-s.hbs file:
    // app/templates/components/w-s.hbs
    Welcome Chat!<br><br>
    
    Received Message: {{message}}<br>
    <button id="sendButtonPressed" {{action "sendButtonPressed"}}>Press Me</button>

    In this template, we have a message property and button that sends an action, sendButtonPressed. When the action is triggered, a message is sent to the server. The message property will display any messages returned from the server.

  3. Update the w-s.js component file so that it can handle the action from the template:
    // app/components/w-s.js
    import Ember from 'ember';
    
    export default Ember.Component.extend({
        websockets: Ember.inject.service(),
        socket: null,
        init() {
          this._super();
          let socket = this.get('websockets').socketFor('ws://localhost:7000/');
          this.set('socket',socket);
          socket.on('open', this.myOpenHandler, this);
          socket.on('message', this.myMessageHandler, this);
          socket.on('close', (event)=> {
            console.log('closed');
          }, this);
        },
        message: '',
    
        myOpenHandler(event) {
          console.log('On open event has been called: ' + event);
        },
    
        myMessageHandler(event) {
          console.log('Message: ' + event.data);
          this.set('message',event.data);
        },
    
        actions: {
          sendButtonPressed() {
            this.get('socket').send('Hello Websocket World');
          }
        }
    });

    The add-on installs a service called websockets in the application. It can be accessed by injecting it into the component using Ember.inject.service. As the property name matches the service name, we don't need to specify the service name in the inject statement.

  4. To begin, we'll set up the init function:
    …
        init() {
          this._super();
          let socket = this.get('websockets').socketFor('ws://localhost:7000/');
          this.set('socket',socket);
          socket.on('open', this.myOpenHandler, this);
          socket.on('message', this.myMessageHandler, this);
          socket.on('close', (event)=> {
            console.log('closed');
          },this);
        },
    …

    The init function in a component is called on when the object is instantiated. You can override this by setting up your own init. To make sure that nothing odd occurs, we must call this._super() so that Ember sets up the component correctly.

    The socket.on method creates three events called open, message, and close. During instantiation, these three event handlers are created. The first one handles events that occur when a connection is made with the server.

    The WebSocket service can be set up using the socketFor method. This tells the service where the server is located.

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

    When the connection is established, a message is logged to the console.

  5. The second event is triggered when a message is received from the server:
    …
        myMessageHandler(event) {
          console.log('Message: ' + event.data);
          this.set('message',event.data);
        },
    …
  6. After a message is received, it's set to the message property. The last event is triggered when the connection with the server is closed:
    …
        socket.on('close', (event)=> {
          console.log('closed');
        }, this);
    ..

    This logs a message to the console.

  7. The sendButtonPressed action creates a message and sends it to the server:
    …
        actions: {
          sendButtonPressed() {
            this.get('socket').send('Hello Websocket World');
          }
        }
    …

    After the action is triggered, we use the existing socket property to send a message out to the server.

  8. Add the w-s component to the ws.hbs route:
    // app/templates/ws.hbs
    {{w-s}}

    The component will render at {{w-s}}.

  9. Load the server and navigate to the w-s route at /ws. You'll see the following message:
    How to do it...

    This message displays the values from the server. Pressing the button sends a message to the server.

    You can see how we can take this simple example and create a complete chat server.

How it works...

WebSockets helps facilitate communication between a server and browser. The browser can send and receive data over sockets. This can be used with event-driven messages or APIs.

There's more...

There are many ways to implement a WebSockets server. A great way to do this is to use the ws library. In the following steps, we'll create a basic WebSockets server to use with this recipe:

  1. Create a new empty directory and run this command:
    $ npm init
    

    Follow the prompts and create your project.

  2. Install the ws package:
    $ npm install ws –save
    

    This will install the ws npm package and save it to the package.json file.

  3. Create a new server.js file. Create a simple WebSockets server:
    // server.js
    var WebSocketServer = require('ws').Server;
    var ws = new WebSocketServer({port: 7000});
    
    
    ws.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
        console.log('received: %s', message);
        ws.send('Hey! Welcome to my websocket challenge!');
    });
    
    
    });
  4. Start the node server:
    $ node ./server.js
    

    This server creates port open at 7000. It then waits for a connection. If it receives a message, it outputs it to the console and returns a new message. This will be displayed in the Ember template file and received by the message handler.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset