Writing TCP server and client socket programs in JAVA

As we have already seen, how to write UDP socket programs in JAVA, now we will write a sample TCP client and server in java.

 $ vim TcpReceiverServer.java 
import java.net.*;
import java.io.*;

public class TcpReceiverServer extends Thread {
        private static int remoteServerPort = 5555;
        private ServerSocket localServerSocket = null;

        public TcpReceiverServer() {
                try {
                        localServerSocket = new ServerSocket(remoteServerPort);
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }

        public void run() {
                while(true) {
                        try {
                                System.out.println("Waiting for client on port " + localServerSocket.getLocalPort() + "...");
                                Socket server = localServerSocket.accept();

                                System.out.println("connected to remote client " + server.getRemoteSocketAddress());
                                DataInputStream in = new DataInputStream(server.getInputStream());

                                System.out.println(in.readUTF());
                                DataOutputStream out = new DataOutputStream(server.getOutputStream());
                                out.writeUTF("Response/Ack to your data received at server : " + server.getLocalSocketAddress() + "\nThank You!");
                                server.close();
                        } catch (SocketTimeoutException s) {
                                System.out.println("Socket timed out!");
                                break;
                        } catch (IOException e) {
                                e.printStackTrace();
                                break;
                        }
                }
        }

        public static void main(String[] args) throws Exception {
                TcpReceiverServer tcpReceiverServer = new TcpReceiverServer();
                tcpReceiverServer.start();
        }

}

Now, lets compile the run the server in one terminal as,

 $ javac TcpReceiverServer.java 
 $ java TcpReceiverServer
Waiting for client on port 5555...

Here, server will be started and it will start listening on a port as defined in source (i.e. 5555 ) , you can use any other port which is free.

Now, open another terminal and start the client as,

 $ vim TcpSenderClient.java 
import java.net.*;
import java.io.*;

public class TcpSenderClient {
        private static String remoteServerAddr = "192.168.1.100";
        private static int remoteServerPort = 5555;

        public static void main(String[] args) throws Exception {
                InetAddress remoteServerInetAddr = InetAddress.getByName(remoteServerAddr);
                Socket localSocket = new Socket(remoteServerInetAddr, remoteServerPort);

                String message = "This is string sent from TcpSenderClient";

                System.out.println("Connected to remote client: " + localSocket.getRemoteSocketAddress());
                OutputStream outToServer = localSocket.getOutputStream(); //pointer to stream which can send data to server
                DataOutputStream out = new DataOutputStream(outToServer);

                out.writeUTF(message + " :  " + localSocket.getLocalSocketAddress()); //data to send to server

                InputStream inFromServer = localSocket.getInputStream(); //pointer to stream which can receive data from server
                DataInputStream in = new DataInputStream(inFromServer);

                System.out.println("Server sent us reply as: " + in.readUTF()); //data received from server
                localSocket.close();
        }
}
 $ javac TcpSenderClient.java 

Now start the client as below, and as shown in received message, it attempted a connection to server IP as mentioned in source, sent a string and received a response from server.

 $ java TcpSenderClient
Connected to remote client: /192.168.1.100:5555
Server sent us reply as: Response/Ack to your data received at server : /192.168.1.100:5555
Thank You!

Now, As soon you started the client, on server side, it will receive a connection from client, receive a string from client and send a reply to client as seen below,

 $ java TcpReceiverServer
Waiting for client on port 5555...
connected to remote client /192.168.1.100:36940
This is string sent from TcpSenderClient :  /192.168.1.100:36940
Waiting for client on port 5555...

And as you can see server again went back into listening .

Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home JAVA Programs Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply