Coders Packet

Communicating between nodes in JAVA using & study InetAddress, socket class.

By Shiroli Nigam

Hi, we will learn how to implement a program to communicate between two nodes using Sockets in JAVA.

In this program, we will use & study InetAddress and most importantly Socket class. With Java networking, we can connect two or more computing devices together to share resources, Socket programming is used to share data between two computing devices. To establish communication with clients ServerSocket class can be used to create a server socket. 

Logic

1) First we will create a client socket and a server socket class.

2) Then we will request a connection to the server.

3) Accept client connection at the server and by using readUTF we will read the message and display the message on output window using writeUTF.

4) To end the connection send "bye", which will close the socket. 

Codes

Server-

import java.net.*;
import java.io.*;

public class server {
    public static void main(String[] args) throws IOException {
        try {
            ServerSocket ss = new ServerSocket(5000);
            Socket s = ss.accept();

            System.out.println("Connected to client");

            DataInputStream in = new DataInputStream(s.getInputStream());
            DataOutputStream out = new DataOutputStream(s.getOutputStream());

            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);

            String s1 = "", s2 = "";

            while (!s1.equals("bye")) {
                s1 = in.readUTF();
                System.out.print("From Client : ");
                System.out.println(s1);
                s2 = br.readLine();
                out.writeUTF(s2);
                out.flush();
            }
            s.close();
        } catch (Exception e) {
            System.out.print("Error");
        }
    }
}

Client

import java.net.*;
import java.io.*;

class client {
    public static void main(String[] args) throws UnknownHostException, IOException {
        try {
            Socket s = new Socket("localhost", 5000);
            DataInputStream in = new DataInputStream(s.getInputStream());
            DataOutputStream out = new DataOutputStream(s.getOutputStream());

            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);

            String s1="", s2="";

            while (!s2.equals("bye")) {
                s2 = br.readLine();
                out.writeUTF(s2);
                s1 = in.readUTF();
                System.out.print("From Server : ");
                System.out.println(s1);
            }
        } catch (Exception e) {
            System.out.print("Error");
        }
    }
}

Output

output

Download project

Reviews Report

Submitted by Shiroli Nigam (shirolinigam)

Download packets of source code on Coders Packet