You might expecting a tutorial on JSON webtokens with Waterlock as i promised you in the last tutorial , but this is not that one. The reason is that when i searched , experimented more on Waterlock , i found an issue with invalidating JSON web-token , i’ve reported the issue in their Github Page. Hope he’ll rectify it. In the meantime we can go for an awesome tutorial on Socket in Sails.js .I’ll use AngularJS here along with Sails. We are going to create a chat application (not a real one :D , a demo piece ;) ) with Sails Sockets and Angular.
Introduction to WebSockets
WebSocket is a protocol providing full-duplex communications channels over a single TCP connection. There are two main continents in the world of WebSockets
- the client (e.g. browser)
- the server (e.g. your routes, controllers, and so forth).
Socket communication comes in handy when we rely heavily on real-time communication between peers/ client-server etc.With the advent of Node.js , real-time communication has become easier than before. You can use sockets to have real-time communication. You Socket.io with Node to make the task easier. Here we are using Sails MVC on Node.js to create our Socket app .
Sails comes with in-built sockets. Sails consist of several functions that can make your task easier . Please have a look at Sails app with its initial configuration .
Create a sails application
Sails provides EJS templating by default. I like to have raw HTML than EJS/JADE . There will be many people like me right ? I hope so :D . So i’ll remove the default templating and will be creating a fresh Bootstwatch + Angular UI.
How can i use HTML files instead of JADE/EJS ? This was a question many people asked me when i started writing about Sails.js
Here is a simple solution. In your Sails App , go to
config/routes.js. You will see following code there
Remove the route to '/' as shown below . Keep it blank
routes.js will look like
Okay !!! now it’s done you can use your HTML files in Sails app . Put your index.html in
assets folder . Sails will now load views from here :)
You can now delete your views folder in your Sails App .The directory structure at this point will as shown below .
Now we are set with initial configuration, so let us move on to the next part . Configuring controllers and models
Define a chat controller and a chat Model
You have Chat model and Chat Controller with you now.
Create Chat Model
Chat model consists of 2 attributes :
- user - defines which user sends the message
- message - defines the message send
user attribute can be autogenerated or a static one for one socket / user input name . A
message is the message obtained through sockets
api/models/ can be modified with above attributes
Write the controller logic
Here is place where we have our socket configuration and default controller actions.
Chat controller has to add new messages and to send message socket clients when a new message is arrived.
I’m adding a new function here
addConv. The file
api/controllers now looks like the one below
addConv checks whether the request is from a socket or not . This can be done by checking
req.isSocket . If it is a
POST request , it means a new message should be added . The message as well as username is obtained via
So here is our logic
When a new Chat Model Instance is created , we will push the corresponding data to connected clients. So here we have to make the clients to watch the model
Chat and get message when new Chat is created
- .watch(request) : This subscribes a client to publishCreate events for the model. Any connections that are “watching” the model class will be automatically subscribed to new model instances that are created using the blueprint create method.
- .publishCreate(data,[request]) : PublishCreate doesn’t actually create anything. It simply publishes information about the creation of a model instance via websockets. PublishCreate is called automatically by the blueprint create action.
Modify the code with corresponding functions
Initially client connects with a GET request to
/chat/addConv/ , then it will be added to subscribe list of Model
Chat .When new additions are done in Chat model . It will be pushed to all clients who watch the changes.
So by this our server side logic is complete . Pretty simple right ? :)
Create Angular UI
Now we will create an Angular frontend that can communicate with the server . So create an
index.html file in the folder
I’m using the following frameworks
- Bootswatch - Paper Theme : This can be used to create a Material Design like interface which is actually cool :)
- Angular JS : Make our job easier :) I don’t think i should talk more about this
index.html will look like
Create an angular app add Chat Controller to it :)\
Socket connection can be initiated with
io.socket.get call to
Now retrieve the chat history upto now.
/chat is in-built API with Sails . This may go down when you go for production , you will have to create your own API to retrieve the chat till now.
NOTE : The default number of records to show in the response from a “find” action is limited to 30 in Sails. This can be modified in
Add the following line
Now let us try to show the chat Messages using Angular JS
Here i’ve used some features of Angular JS
- chat iterator
orderBy - filter in module ng Orders a specified array by the expression predicate. It is ordered alphabetically for strings and numerically for numbers. Note: if you notice numbers are not being sorted correctly, make sure they are actually being saved as numbers and not strings.
orderBy_expression | orderBy : predicate : reverse
$scope.reverse to false
Now let us try to get socket messages.
The publishCreate socket message to subscribers will include the following properties:
- id - the id attribute of the new model instance
- verb - “created” (a string)
- data - an object– the attributes and values of the new model instance
io.socket.on() : Starts listening for server-sent events from Sails with the specified eventIdentity. Will trigger the provided callback function when a matching event is received.
Check whether the
created. If so add the data to current ChatList in AngularJS.
$scope.$digest() function iterates through all the watches in the $scope object, and its child $scope objects (if it has any). When $digest() iterates over the watches, it calls the value function for each watch. If the value returned by the value function is different than the value it returned the last time it was called, the listener function for that watch is called.
The $digest() function is called whenever AngularJS thinks it is necessary. For instance, after a button click handler has been executed, or after an AJAX call returns (after the done() / fail() callback function has been executed).
Alternatively you can use
Now we add some input fields to the page to take input from user.
We can take username and message from user. Edit the HTML code as follows
I use two models here
chatMessage. On send call
sendMsg() function which is described as
io.socket.post does the same function as POST , but through sockets :)
So the Angular code will now look like
I’ve set the chatUser to
nikkyBot which can be edited by user.
Now let us add some css customisations
All set , ready to rock !!! Lift your app .
Yeah!!!! It works :)
Hope you have enjoyed the tutorial . Ping me if you need any king of assistance . So See you till the next awesome tutorial :) Bye