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.



Thursday, October 30, 2014

JavaFX dialogs

The JavaFX project doesn't have dialog controls, so when I wanted to add dialogs to my project I used the dialog controls from the fxexperience project, they release you from all the trouble of creating your own control, but recently they announced that the dialog controls will be in a separate project (announcing-controlsfx-8-20-7) deprecating the current controls.

The new project is called openjfx dialogs and it is located right here https://bitbucket.org/controlsfx/openjfx-dialogs. Since right now it doesn't contain any documentation I will explain you how to start using it and ease the way to start adopting them.

To start working first download the project repository from here bitbucket.org/controlsfx/openjfx-dialogs, in the left side there is a link to download, it downloads a zip file, unzip it wherever you wan to.

Next the project needs to be build, to do this we will need gradle, for thoose who don't know what is gradle here it is a brief description about it:

"Gradle combines the power and flexibility of Ant with the dependency management and conventions of Maven into a more effective way to build"

I'm not going to explain deeper gradle since it is another topic and this post wouldn't be enough to explain it.

You can download and install gradle form here www.gradle.org, the project already contains a version of gradle you can just run the gradlew.bat file. Either you install it or use the version of the project, run the following command at the root of the project:

    gradle build

If the project is built correctly you will find the folders build/lib under the root of the project, under these folders the openjfx-dialogs-X.X.X.jar is located we will need this jar to add the dialog controls.

Now let's create an example to test the dialogs an see how they work, I'm going to use Netbeans to develop this example.

Let's create a javafx application project:


Let's name the project Dialogs, keep selected the checkbox "Create application class", then click finish.

Add to project the openjfx-dialogs jar, to do this over the project right click and select "properties" option. In the properties select the "libraries" option


Click over the Add Jar/Folder button, and select the jar previously built "openjfx-dialogs-X.X.X.jar".


With these steps everything is set to start creating dialogs, in the previous version the code to create a dialog was kind of messy and not intuitive from of my point of view, this is an example:

It uses the builder pattern wikipedia.org/wiki/Builder_pattern, a single class did handle all the types of dialogs, but now this code is deprecated. You can find more about the deprecated dialogs right here controlsfx.bitbucket.org/index.html?org/controlsfx/dialog/Dialogs.html

In the new version each type of dialog has its own class making the code clearer and more intuitive, this is from my point of view. At this point the types of dialogs are javafx.scene.control.Alert, javafx.scene.control.ChoiceDialog and javafx.scene.control.TextInputDialog.

Lets create an alert dialog, in the class created in the project change it to display the dialog as the following example:

From the example above an Alert object is created and it is passed a type of alert dialog, in this case is confirmation but there are others as error, information, warning, and so on.

In the button's click event the show() is called to display the dialog, but this method doesn't wait the dialog to close, the method showAndWait() waits the dialog to close and returns an Optional object with the button typed if that was the case.

The following example uses a text input dialog:

From the example above the only difference is that the showAndWait() method returns an Optional object with the content of the input element from the dialog.

The ChoiceDialog displays a dialog with a combo control with a set of values, the following example show how to use it:

From the example above you can see that the options are passed through the constructor and later through the items property and uses the same mechanism as the TextInputDialog to retrieve the value selected.

As I said before since the project is not finish and right now there is no documentation, I hope that with this post you can more easily adopt this new version or start using it.

Friday, October 17, 2014

JavaFX workaround for rotate text on tabpane tab

I have not much of experience with JavaFX, but I've been using it since almost over a year by now. I found that the tabs from the tabpane control have a restriction, when they are placed by a side either right or left the text can not be placed horizontal, the following image shows the behavior.


The issue is that the text is not displayed horizontally and it is hard to read, and javaFX does not provide a solution to it, actually there is feature request to it https://javafx-jira.kenai.com/browse/RT-19547 but it seems that it will not happen soon.

I found some workarounds to it, but they have many issues such as the text doesn't properly resize the tab width, so I'm going to describe the workaround that I did, hoping that it could be helpful to you.

A solution that I found from this post http://stackoverflow.com/questions/16708578/javafx-2-0-tabpane-tabs-at-left-and-keep-tab-header-horizontal , mentions to add the following style:

Which works fine:

But what if you have multiple tabs in your application and this tabs do not have the tabs by a side, it will also rotate the text of this tabs and will complicate everything.


Another issue is, if the characters of the text increases the size also increases but not only its width but also its height:


Due to all this issues this workaround and others seem to work fine only in certain scenarios.
My workaround is not better than them, but it tries to avoid these issues.
First, only rotate the tabs you want to rotate, to do this create a CSS class:



Then add it to the tabs objects you want to rotate:



Then create a CSS class to handle the size for the TabPane in which you are rotating the tabs:

Add this class to the TabPane object:

With this you will restrict the size of your tabs and they will not get bigger if the text increases. The limitation it has is that the amount of characters depends on the size you set to the TabPane object.




As I said I'm not an expert on javaFX and I found this solution to this issue that seems to be different to others and might help you.
If you have a different solution before this issue is fixed tell me about it.



Monday, June 9, 2014

Debug in node.js

A few days ago someone asked me if I knew how to debug in node.js and to be honest I was debugging with the console object, although it is effective I thought there should be better ways to debug a script, so I'm going to explain you my findings and hope to help someone that was in the same position as me.

So let's start with the simplest way to debug with the console object.


Save the script and run it, the console will output in each iteration the value of the variables used in this case "i" and "sum", like the following:

Iteration:0, sum:0
Iteration:1, sum:1
Iteration:2, sum:3
Iteration:3, sum:6
Iteration:4, sum:10
Iteration:5, sum:15
Iteration:6, sum:21
Iteration:7, sum:28
Iteration:8, sum:36
Iteration:9, sum:45

The console object has other methods besides log(), you can find more about it in the following link:

http://nodejs.org/api/stdio.html

Since V8 node comes with a debugger, it has a built in client for this debugger to use it just add the debug argument when start running the script. Save the previous script as scriptDebug.js then type the following command to start the debugger:

               node debug scriptDebug.js

After that you will see a prompt to the debugger client as the following:

< debugger listening on port 5858
connecting... ok
break in scriptDebug.js:1
  1 var sum = 0;
  2
  3 for(i=0;i<10;i++) {
debug>

Now the debug client support some basic commands to debug the script, here are some of them:
  • cont, c - Continue execution
  • next, n - Step next
  • step, s - Step in
  • out, o - Step out
  • pause - Pause running code (like pause button in Developer Tools)
  • setBreakpoint(), sb() - Set breakpoint on current line
  • clearBreakpoint, cb(...) - Clear breakpoint
  • .....
In the debugg mode if you type the command cont as this:

< debugger listening on port 5858
connecting... ok
break in scriptDebug.js:1
  1 var sum = 0;
  2
  3 for(i=0;i<10;i++) {
debug> cont
< Iteration:0, sum:0
< Iteration:1, sum:1
< Iteration:2, sum:3
< Iteration:3, sum:6
< Iteration:4, sum:10
< Iteration:5, sum:15
< Iteration:6, sum:21
< Iteration:7, sum:28
< Iteration:8, sum:36
< Iteration:9, sum:45
program terminated

You will see will be the output of the program, this is because the is no breakpoint in the code.

To set a break point you could use the command sb(), for example to set a break point in the line 5, it would be like this:

connecting... ok
break in scriptDebug.js:1
  1 var sum = 0;
  2
  3 for(i=0;i<10;i++) {
debug> sb(5);
  1 var sum = 0;
  2
  3 for(i=0;i<10;i++) {
  4 sum = sum + i;
* 5  console.log('Iteration:' + i +', sum:' + sum);
  6 }

Now every time a continue command is given it will stop in the breakpoint, as the following examples shows:

debug> cont
< Iteration:0, sum:0
break in scriptDebug.js:5
  3 for(i=0;i<10;i++) {
  4 sum = sum + i;
* 5  console.log('Iteration:' + i +', sum:' + sum);
  6 }
  
Another way to place a breakpoint is to set the debugger instruction in your code as the following example:



Once you can go through your code, what is missing is to inspect the values of the variables in your program, to do this let's use the watch command in the script we have used so far, the following example show how to use it:

$ node debug scriptDebug.js
< debugger listening on port 5858
connecting... ok
break in scriptDebug.js:1
  1 var sum = 0;
  2 
  3 for(i=0;i<10;i++) {
debug> watch('sum')
debug> cont
< Iteration:0, sum:0
break in scriptDebug.js:6
Watchers:
  0: sum = 0

  4 sum = sum + i;
  5  console.log('Iteration:' + i +', sum:' + sum);
  6  debugger;
  7 }
  8 
debug> cont
break in scriptDebug.js:6
< Iteration:1, sum:1
Watchers:
  0: sum = 1

  4 sum = sum + i;
  5  console.log('Iteration:' + i +', sum:' + sum);
  6  debugger;
  7 }
  8 

As you can see now every time a breakpoint is found the variable sum is printed with its value.

With this tool you can easily go through your code, stop wherever you want and do many more things, you can find all the instructions in the following link:

http://nodejs.org/api/debugger.html

The debbuger that comes with node.js is very powerful but still is a command based utility, there are debbugers with more visual help, lets use node inspector to have a visual aid to debug our script.

First lets install globally node inspector, with the help of npm use the following command:

        $ npm install -g node-inspector

With node inspector installed let's start it with the following command:

$ node-inspector
Node Inspector v0.7.3
Visit http://127.0.0.1:8080/debug?port=5858 to start debugging.

With node inspector running in other terminal you have to start in debug mode your application with the following command:

$ node --debug-brk scriptDebug.js
debugger listening on port 5858

The --debug-brk option is a node inspector option which starts to debug the script and stops it in the first line.

Now let's open a browser with url indicated "http://127.0.0.1:8080/debug?port=5858" by node inspector, you will see the following console:


As you can see the script is displayed and in the right side there is a window that displays all the information about the runtime values of the script, as in the upper right side there are some navigation buttons to go through the script.

With node inspector the debugging of a script is made so much easier because it is a visual tool and all the commands are a click away.

You can find more about node inspector in the following link:
https://github.com/node-inspector/node-inspector

This is a brief example of how to start using the debug tools of node.js and I hope it is useful to you.





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.  





Sunday, April 13, 2014

Different ways to run scripts in node.js

Well now I have some weeks learning node, the easiest way to run a script is through  the node command, lets start with a simple script:



Save it as server.js If you want to run this script all you have to do is go to the directory where the script is and run the following command:

                           node server.js

Another way to run a script is through the npm command, it requires a file named package.json at the root of the project, this way is more sophisticated because in the package.json file you can specify a command to run a script, so you can have several commands each one mapped to a script.
Also it helps to configure dependencies, versions and a lot of other stuff, you can find more about the package.json configuration in the following link:
                   https://www.npmjs.org/doc/json.html

Well for the purpose of the blog the file package.json will be very simple just to show how it works, so it will contain the following:


In the file the start command is mapped to the server.js script, once the file is saved in the directory where sript is located the following command will run the script:

                          npm start

Another way to run a script is with the help of packages one of them is nodemon (http://nodemon.io/), it stands for node monitor.

The description of nodemon says that it is a utility that will monitor for any changes in your source and automatically restart your server. Perfect for development. Using nodemon instead of node to run your code, and now your process will automatically restart when your code changes.

To install nodemon jus run the following command:

                         npm install -g nodemon

The -g means that it will install nodemon in a global way, you don't have to install it for every project.

Once installed you can see it working, just replace the node command for nodemon and run the script:

                         nodemon server.js

To see it working type the address http://127.0.0.1:1337/ in your browser and see the output, then modify the script to output instead "Hello world" to something else, reload the browser and see that the changes are reflect, so this is the big advantage of using nodemon you don't have to waste any time running the scripts while developing them.

Another package that does the same as nodemon is run (https://www.npmjs.org/package/run), install it just like nodemon:

                         npm install -g run

Then run the script with the run command

                         run server.js

Do the same exercise go the address http://127.0.0.1:1337/  see the output and modify the script, reload the page and see the changes.

So far in my way to node these are the different ways to run scripts, I hope you can learn something new from it.

Friday, March 21, 2014

Creating processes in node.js

In some of my previous posts I started comparing some of the features of node.js with java and since then my interest has started to grow for node.js.

One thing I just learned is that node runs in a single thread mode, it uses an event-driven paradigm to handle concurrency.

Well that's fine but what about parallel processes how can you take advantage of this when you are in a single thread program, well node.js has some mechanisms to create processes and take advantage of parallel computing, and I will tell you how.

First we will need a process to run as a worker, there could be many instances running of this process at the same time.

For the purpose of this blog this process will have just a log to console, also any kind of process can be created not just node process, but also for the blog I will use just this.

For creating a child process the child_process module is required, this module has different ways to create process.

The exec method of the child_process runs a command in a shell and buffers the output. It has the following signature:

               child_process.exec(command, [options], callback)


In the example the command "node worker.js i"  is executed where i is a parameter passed to the process.
Also a callback function is passed and it is called when the process terminates and allows to read and process the output from it.

After running the example the following should be printed in console for each process created.

stdout: Process 0 at work
stderr:

Child process exited with exit code 0

The spawn method of the child_process module launches a new process with a given command, it has the following signature:

               child_process.spawn(command, [args], [options])


After running the example the following should be printed in console for each process created.

stdout: Process 0 at work

child process exited with code 0

Exec() and spawn() both create processes, but they differ in what they return, spawn returns streams (stdout & stderr), while exec returns a buffer with a max size. Spawn() should be used when the process returns large amount of data.

Another difference is that spawn() starts receiving the response as soon as the process starts executing, and exec() otherwise waits for the process to end and tries to return all the buffered data at once

The fork method is a special case of the spawn() functionality, it only creates Node processes. Its signature is the following:


              child_process.fork(modulePath, [args], [options])

After running the example the following should be printed in console for each process created.

Process 0 at work
child process exited with code 0

Node.js also has the cluster module and also allows to create processes, the definition of the cluster module says: "A single instance of Node runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node processes to handle the load".

From the example you can notice that the cluster module is imported, once imported you can call fork() method to create a new child process, after calling fork() the same process will run but as a child, to distinguish if the process is running as a Master or child the cluster module has the isMaster() and isWorker() methods.

After running the example above, the following should be printed.

Master Forking!!!!
Worker 4984 is online.
....
Child process running!!!
....


You can find more information about these modules in the following links:
http://nodejs.org/api/child_process.html
http://nodejs.org/api/cluster.html

Node.js says that runs in a single thread mode, but as with this brief example, I show that node.js has different mechanisms to create processes and to take advantage of multiple processors.