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.
$ 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.
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.
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.
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.
… myMessageHandler(event) { console.log('Message: ' + event.data); this.set('message',event.data); }, …
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.
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.
w-s
component to the ws.hbs
route:// app/templates/ws.hbs {{w-s}}
w-s
route at /ws
. You'll see the following message: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.
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 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:
$ npm init
Follow the prompts and create your project.
ws
package:$ npm install ws –save
This will install the ws
npm
package and save it to the package.json
file.
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!'); }); });
$ 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.