Why socket programming?
With the escalation of
distributed computing, single software needs to communicate with Internet or
devices (may be another computer) on a network in order to carry out a task.
Socket is one of the
fundamental aspect in computing which allows to communicate over a network
using standard mechanisms, such as stream communication protocols (TCP/IP),
datagram communication protocols (UDP/IP).
Where can I find socket
in real life?
If you're reading this, that
means you are consuming the precious advantages of socket programming.
Yes..Indeed, your browser
works as a client to communicate with the Internet, which is end of the day, a software.
In addition to that peer-to-peer file transfer programs, instant messaging
services, remote device connectivity (pay your bills from debit or credit card)
for transactions can be best examples.
How socket applications work?
Nutshell, it’s more or less
like getting a telephone call to one of your friend. Requires two parties and
one acts as a client (caller) while the other as a server (receiver). In order
to get a call, you need to know the specific number belongs to your receiver,
which is like host and the port of the server end of the day in network
programming.
If you know the exact host
and the port which has been exposed to a certain service, you can establish a
connection over TCP/IP or UDP/IP to communicate. In order to establish the
connectivity, you need to declare a socket while the sever listening to exact
same socket.
It’s like you’re dialling to
your friends’ phone, you have to wait until your friend accepts the call. Once
he/she does accepts your call, then stats the communication until one of you
hang (cut the connection) the phone. Exact same principle applies for the
sockets as well, once you established the connectivity, you’re good to
communicate and once you’re done connection close.
Have a look on bellow figure
(1.1) to get further understanding on client-server communication.
figure 1.1
TCP/IP or UDP/IP?
The base protocol of a
socket implementation highly varies on the requirement.
TCP/IP (Transfer Control
Protocol) is a streaming protocol which allows you to perform multiple bidirectional
communication without limitation, once opened the socket till the close
operation.
But when it comes to
datagram protocols like UDP/IP (User Datagram Protocol), it allows
bidirectional communication but requires authentication token per every sprint.
And also UDP/IP maintains data limits for communication at each sprint.
In general, if you want a
quick response sprints or to implement your own security infrastructure, implementing
sockets over UDP would be an ideal. But for commonly used interfaces or for services
TCP plays a better roll but with proper security.
Socket Programming in JAVA
In Java java.net.Socket class implements the Socket class and as the listener
(server) has been implemented at java.net.ServerSocket.
Let’s code a simple client named ClientSocketImp.java as follows:
package com.manish.socket.client;
import java.net.*;
import java.io.*;
public class ClientSocketImpl {
private static String
reqMessage = "135.90";
private static String
host = "127.0.0.1";
private static int
port = 7892;
private static Socket
socket = null;
private static
ObjectOutputStream objectOutputStream = null;
private static
ObjectInputStream objectInputStream = null;
public static void
main(String[] args) throws UnknownHostException, IOException,
ClassNotFoundException, InterruptedException {
socket =
new Socket(host, port);
objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
System.out.println("ACQUIRING SERVER CONNECTIVITY....");
objectOutputStream.writeObject(reqMessage);
objectInputStream = new ObjectInputStream(socket.getInputStream());
String
message = (String) objectInputStream.readObject();
System.out.println("RESPONSE : " + message);
objectInputStream.close();
objectOutputStream.close();
}
}
Okay, one more tiny step..Let’s code
a simple server named SocketServerImpl.java as follows.
package com.manish.socket.client;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import
java.lang.ClassNotFoundException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.MessageFormat;
public class SocketServerExample {
private static
ServerSocket server;
private static int
port = 7892;
private static String
response;
public static void
main(String args[]) throws IOException, ClassNotFoundException {
server =
new ServerSocket(port);
while(true) {
System.out.println("WAITING FOR A CLIENT REQUEST...");
Socket socket = server.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
double value = 0.00;
try {
value = Double.parseDouble(message.trim());
value += returnInterest(value);
response = MessageFormat.format("Your interest +
amount Rs {0}", value);
} catch (NumberFormatException e) {
response = "Invalid request";
e.printStackTrace();
}
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(response);
ois.close();
oos.close();
socket.close();
if(message.equals("-1")) {
break;
}
}
server.close();
}
private static Double
returnInterest(Double amount) {
if(amount < 10) {
return ((amount/100)*5.2);
} else
if (amount < 50) {
return ((amount/100)*8.1);
} else
if (amount < 100) {
return ((amount/100)*10.3);
} else {
return ((amount/100)*12.5);
}
}
}
Okay..Now done...!
First run the server class and then
the client. This is a very simple interest returning application, where a
client can send an amount to server over a socket and get the interest added
amount as the response.
You can try this out by yourself and
try to fetch something better out of it...! Enjoy and good luck..!