Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Communicating Node.js and Java via Sockets

See in this article how to build a small and real-time application using Java and Node.js creating a communication between both sides through sockets.

It is increasingly greater the interaction between the user and the web, through various means, such as online games, blogs, chats, interactions on social networks, etc. All this demand requires that communication between applications, client and server, become even faster, serving a large number of concurrent users efficiently.

Current technologies that enable "real-time" include: Node.js, NoSQL databases (like Mongodb), Socket.IO, among others.

In this article we build a simple application of real-time communication, using Java in the client and Node.js on the server side. With the help of this article you could build Java applications (web, mobile, etc.) communicating with real-time technologies.

Let's build a simple system based on "ping-pong" messaging style.

For this, the following tools are required:

  • Linux server with Node.js already installed (apt-get install nodejs), or equivalent in other OS.
  • Java development environment (Eclipse IDE).

See in Links section all the links necessary to download these tools.

This article provides the code for you to mount a small engine of real-time communication with Java and Node.js From these working examples, you can move forward, increasing functionalities according to your needs.

In Listing 1, we have the server code with Node.js.

Listing 1. Server source code using Node.js.

var net = require('net');


var HOST = '127.0.0.1'; // parameterize the IP of the Listen
var PORT = 6969; // TCP LISTEN port


// Create an instance of the Server and waits for a conexão
net.createServer(function(sock) {


  // Receives a connection - a socket object is associated to the connection automatically
  console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);


  // Add a 'data' - "event handler" in this socket instance
  sock.on('data', function(data) {
	  // data was received in the socket 
	  // Writes the received message back to the socket (echo)
	  sock.write(data);
  });


  // Add a 'close' - "event handler" in this socket instance
  sock.on('close', function(data) {
	  // closed connection
	  console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
  });


}).listen(PORT, HOST);


console.log('Server listening on ' + HOST +':'+ PORT);

We have some important points to note in the above code: early in the script, parameterize the IP and port where the Node server will do the Listen. Change the 127.0.0.1 to the real IP (valid) of your server, as follows:

var HOST = '127.0.0.1'; // parameterize the IP of the Listen 
var PORT = 6969; // TCP LISTEN port

See below the function that is triggered when a new connection arrives, simply doing an echo back to the client program:

// Add a 'data' - "event handler" in this socket instance
  sock.on('data', function(data) {
 // data was received in the socket 
 // Writes the received message back to the socket (echo)
 sock.write(data);
  });

In Listing 2 we have the Java client code that opens a socket connection with the server, sends a message and receives it back, printing it on the screen.

Listing 2. Java client source code.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;


public class NodeJsEcho {
	// socket object
	private Socket socket = null;


	public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException {
		// class instance
		NodeJsEcho client = new NodeJsEcho();


		// socket tcp connection
		String ip = "1.1.1.1";
		int port = 6969;
		client.socketConnect(ip, port);


		// writes and receives the message
		String message = "message123";


		System.out.println("Sending: " + message);
		String returnStr = client.echo(message);
		System.out.println("Receiving: " + returnStr);
	}


	// make the connection with the socket
	private void socketConnect(String ip, int port) throws UnknownHostException, IOException {
		System.out.println("[Connecting to socket...]");
		this.socket = new Socket(ip, port);
	}


	// writes and receives the full message int the socket (String)
	public String echo(String message) {
		try {
			// out & in 
			PrintWriter out = new PrintWriter(getSocket().getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(getSocket().getInputStream()));


			// writes str in the socket and read
			out.println(message);
			String returnStr = in .readLine();
			return returnStr;


		} catch (IOException e) {
			e.printStackTrace();
		}


		return null;
	}


	// get the socket instance
	private Socket getSocket() {
		return socket;
	}
}

Remember the IP parameterization and port where the client in java will connect with the nodejs server. Change the IP 1.1.1.1 to a valid IP where it hosted the nodejs application, as the code below:

// class instance
NodeJsEcho client = new NodeJsEcho();

// socket tcp connection
String ip = "1.1.1.1";
int port = 6969;
client.socketConnect(ip, port);

In Listing 3 we highlight the method that writes and receives the message in the socket (nodejs).

Listing 3. Sending and receiving messages

// writes and receives the full message int the socket (String)
public String echo(String message) {
	try {
		// out & in 
		PrintWriter out = new PrintWriter(getSocket().getOutputStream(), true);
		BufferedReader in = new BufferedReader(new InputStreamReader(getSocket().getInputStream()));


		// writes str in the socket and read
		out.println(message);
		String returnStr = in .readLine();
		return returnStr;


	} catch (IOException e) {
		e.printStackTrace();
	}


	return null;
}

Now, in Figure 1 we have the Eclipse console printscreen. When executing the java client in this IDE, you should get a similar screen.

Figure 1. Compilation Results

Conclusion

This is just a simple demonstration of all the Node.js power when communicating with other platforms in the server side, such as Java. You can use this code to develop any kind of applications with Java to connect with Node.js, such as mobile, desktop, or web ones. Now just evolve this simple application to your needs. I hope you enjoyed it. Good luck!



Julio is a System analyst and enthusiast of Information Technology. He is currently a developer at iFactory Solutions company, working in the development of strategic systems, is also a JAVA instructor. He has knowledge and experi...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login