Showing posts with label websockets. Show all posts
Showing posts with label websockets. Show all posts

Wednesday, August 12, 2015

Websockets in node.js

In this post I'll show you how to start using websockets in node.js, the different types of modules there are, how to install them and use them to develop a simple example.

For those who don't know what websockets is about, here is a brief introduction:

Wikipedia says "WebSocket is a protocol providing full-duplex communications channels over a single TCP connection", this means that in a client-server communication the client as the server can send a message leaving behind the request-response protocol, where the exchange is always initiated by the client (usually a browser) and the server cannot send any data without the client requesting it first.

It also says "WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application", websockets was introduced in the clients or browsers since the html5 specification.

If you want to know more about websockets refer to the following links:
http://www.websocket.org/
http://en.wikipedia.org/wiki/WebSocket
https://developer.mozilla.org/en/docs/WebSockets

WS


Let's start with the first module "WS" , to start using it it needs to be installed so the following commands install the library:

To install the module to the current directory use the following command:
     $ npm install ws

To install the module in a global way use the following command:
    $ npm install ws -g

Once install it we can create an example using this module, the code below shows how to create a simple server with ws:


Save the file as ws_server.js, from the code you can see that the server will be running in port 8080, any request to this port the server will attend it. To create a client use the code below:


Save the file as ws_client.js and now lets run them, to run the server just type the following commands:

Server:
   $ node ws_server.js
   Msg received in server: Msg from client

Client:
   $ node ws_client.js
   Msg received in client: Msg from server

From the output you can see that the server starts and listens to any message when the client starts it also listens to messages and it sends a message, then the server receives it and answers this message

To find more about ws module go the following link https://github.com/einaros/ws  is the page of the library.

WebSocket


Lets try another module for websocket, the WebSocket-Node module, this module has more requirements, needs c++ and python to compile the native modules but they are optional but its efficiency decreases if they are not installed, if you are a windows user you will find harder to install.

To install WebSocket-Node module use the following command and use -g option to install it globally:

    $ npm install websocket -g

Once installed the module lets proceed to create the example:


Save the file as websocket_server.js. It creates a server for websockets that listens requests at the url ws://localhost:8080/example, in the code you can see that the port is configured at the instruction server.listen(8080), and the path is formed with request.accept('example', request.origin); .

Let's create a client for the server:


Save the file as websocket_client.js, from the code you can see that the client creates a connection to the server using the instruction client.connect('ws://localhost:8080/', 'example'); ,when a connection is done a message is sent to the server and the server should respond to the client with also a message.

Now lets run the scripts using the following commands:

Server:
   $ node websocket_server.js
   Received Message: Message from client

Client:
   $ node websocket_client.js
   Received: 'Msg from server'

The messages that the server and client are sending should be printed in the console if everything works as expected, if a problem happens with  the connection you should see a message like this "Connection Error: Error: connect ECONNREFUSED".

To find more about websocket module go the following link https://github.com/theturtle32/WebSocket-Node  is the page of the library.

engine.io


Another module to use for creating websockets is engine.io, although this module is part of a bigger framework you can still use this module to create websockets.

To install the module use the following command, to set it globally use the -g option:
    $ npm install engine.io -g

To create a client for this module the module "engine.io-client" is required, lets install the module:
    $ npm install engine.io-client

Lets create an example of a server:


Save the file as engineio_server.js, from the code you can see the configuration needed to run the server, it is pretty simple.

Now lets create a client for this server:


Save the file as engineio_client.js and lets run the example with the following commands:

Server:
        $ node engineio_server.js
         Msg Received at server:Msg from client

Client:
       $ node engineio_client.js
        Msg Received at client:Msg from server

As in the others examples if everything works as expected you should see the messages exchanged by the server and the client in console.

To find more about engine.io module go the following link https://github.com/socketio/engine.io  is the page of the library.

There are many other libraries that can be used to create websockets with nodejs, every one with its pros and cons but it would take another post to discuss this topic. I guess the hardest part would be to choose which library to use.

I wish this post helped you to better understand what websocket is and how to implement it in nodejs.



Wednesday, May 28, 2014

Websockets in Java EE 7 with wildfly

In the past few weeks I've trying the websockets technology introduced in JEE 7 and I would like to share you how to develop a simple example of it, for those who don't know what is about websockets, here is a brief introduction.

Wikipedia says "WebSocket is a protocol providing full-duplex communications channels over a single TCP connection", this means that in a client-server communication the client as the server can send a message leaving behind the request-response protocol, where the exchange is always initiated by the client (usually a browser) and the server cannot send any data without the client requesting it first.

It also says "WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application", websockets was introduced in the clients or browsers since the html5 specification, and in the Java servers since the JEE 7 version and the specification  JSR 356.

If you want to know more about websockets refer to the following links:

I'm going to use the wildfy 8 as server the open source version of jboss, you can download it from here http://wildfly.org/downloads/, and as for the IDE I'm going to use JBoss tools, you can download it from here http://tools.jboss.org/downloads/ .

To set up wildfly with eclipse you can use the following link for instructions:  http://planet.jboss.org/post/getting_started_with_jboss_tools_and_wildfly_tech_tip_5

Once you have everything installed and integrated lets start creating a websocket application.
lets create a new project, select new project and from the options presented choose dynamic web project, set the name of the project as websockets and the target runtime to wildfy 8.

The Java API for WebSocket consists of the following packages.

  • The javax.websocket.server package contains annotations, classes, and interfaces to create and configure server endpoints.
  • The javax.websocket package contains annotations, classes, interfaces, and exceptions that are common to client and server endpoints.

Now lets create a new server endpoint class, this class will receive the messages from the client and also it could send messages to the client.


From the class above notice the @ServerEndpoint annotation, it indicates the class will be a socket endpoint, it takes a string ("example") as parameter this will be the URI of the endpoint.

The methods of the class are annotated with @OnOpen, @OnMessage, @OnClose annotations, these indicate the lifecycle of endpoint here is a brief description of them:

AnnotationEventExample
OnOpenConnection opened
@OnOpen
public void open(Session session, 
                 EndpointConfig conf) { }
OnMessageMessage received
@OnMessage
public void message(Session session, 
                    String msg) { }
OnErrorConnection error
@OnError
public void error(Session session, 
                  Throwable error) { }
OnCloseConnection closed
@OnClose
public void close(Session session, 
                  CloseReason reason) { }




The endpoint now is ready to start a conversation so deploy it in wildfy and lets create a html client to communicate with this endpoint.


In the previous html file the only thing to notice is the simple script that creates a connection to the endpoint, from the url "ws://localhost:8080/websockets/example" used check the name of the application and the URI of the endpoint.

If you open the html file on browser that supports web sockets you should see the message "Web Socket is connected!!" and in the server you should see in console the message "Open session:...". This indicates that the communication has been established between the client and the server.

To now more about the WebSocket javascript interface the following link will help:
http://www.w3.org/TR/2011/WD-websockets-20110419/

Let's create a message and send it from the client to the server. To do this let's just add the following function in the javascript section of the html file.


With this function the ws variable calls the sends() method and sends the message to the server.
To call this function just add a html link and call it.


Let's test it click on the link and you should see the following message on server's console: "Received : Message to server from client, session:..."

Now to simulate a request-response communication lets return a message from the @OnMessage method in the websocket endpoint in the server.


Deploy it and test it, you should get the following sequence of messages:

  1. Browser displays "Web sockect is connected".
  2. After calling send(), server console diplays: Received : Message to server from client, session:
  3. Browser displays "Received, Response from the server"
To demonstrate full duplex communication lets send messages from the server without any request from the client. To do this, lets add and asynchronous task to send messages.



Notice that the @Stateless annotation has been added to the endpoint, it is required to send messages asynchronously, with this now the endpoint is also an EJB, also the endpoint makes use of the ManagedExecutorService resource, it takes runnables and executes them, this is done on the @OnOpen method so when the conversation starts the runnables are set.
In the runnable we wait for 10 seconds and then sends a message to the client this is done without receiving any previous message and this is repeated 3 times so during 30 seconds, your browser should be receiving the message "Received, Message from server".

With this is demonstrated the full-duplex communication this is a message can be sent without any prior message or request.

Well this is basically a simple example that demonstrates how web sockets work, in further post I will keep showing more of their functionality.