Tuesday, 13 September 2016

Using Sockets

Sockets are used to communicate 2 different processes  on same or different machines.

Application ->
For Eg.
Suppose a JavaScript Application want to send Message to Java Application(JAR file.)
Hence we can communicate JavaScript and Java Application using sockets.

Also, If processes are running on different machines then socket is used as a common ground to communicate both processes.

How to use ->
Socket has 2 parts ->
1.Client -> App which sents/request data to another app
2.Server -> App which processes/responds to sent request.

In Order to make Socket Object we need IP and Port.

Here I am using an example in which client sends 2 no a and b to server. Server then adds them and returns the result.

I am using nodeJs and Javascript  

Client Part (Client.js)
Client selects IP and PORT to establish Socket.
    
var JsonSocket = require('json-socket');//Client Details
var HOST = "172.16.207.151";
var PORT = "6969";
//same port where server is listening...
// Make a sokcet with JSONSocket
var socket = new JsonSocket(new net.Socket());
//Create instance of server and wait for connection
socket.connect(PORT, HOST);
console.log('Server listening on ' + HOST + ':' + PORT);

socket.on('connect', function () {
//Don't send until we're connected
//On connection sending no a and b to server to multiply.
    socket.sendMessage({ a: 5, b: 7 });
   
//on getting result from server print it.
    socket.on('message', function(message) {
        console.log('The result is: '+message.result);
    });
});








Server Part (Server.js)
Sever only needs to listen to port where client is sending data

var net = require('net');
JsonSocket = require('json-socket');
var PORT = "6969";
var server = net.createServer();
server.listen(PORT);
server.on('connection', function(socket) {
//This is a standard net.Socket
    socket = new JsonSocket(socket);
//Now we've decorated the net.Socket to be a JsonSocket
    socket.on('message', function (message) {
        console.log("Message Received on server");
        var result = message.a + message.b;
        socket.sendEndMessage({result: result});
    });
});
How to test?
First run server.js and then client.js
output: 
on Client Side->
Server listening on 172.16.207.151:6969
The result is: 12

on Server side->
Message Received on server
 

I Hope this helps.


No comments:

Post a Comment