Socket Programming in Java – Established Java Socket Connection

This topic may seem intimidating at first but once you understand the nitty-gritty details about it, it is all going to be very easy.

Very soon you will be able to run your own servers from the comfort of your laptop! So what are sockets in the first place?

A very abstract definition of it could be that a socket is an interface between the application and the network. When you combine an IP address and a port you get a socket.

Let us dive in!

What is Socket Programming in Java?

Java being a high-level language can be useful for designing server-client connections. You can achieve this by socket programming.

There are some classes that we need to learn about before we progress into programming.

Stay updated with latest technology trends
Join DataFlair on Telegram!!

Java Socket Class

The socket class is useful for creating a socket. These sockets act as endpoints for communication between two machines.

There are few ways by which we can initialize the Socket object:

ways to initialize the socket object

  • Socket() – This does not connect a socket. It just creates one.
  • Socket(InetAddress address, int port, InetAddress LocalAddress, int localport) – This connects the local address and the port to the remote address and the remote port. However, do remember that they have to be on the same network.
  • Socket(InetAddress address, in port) – This simply connects the IP address and the port to the local socket.
  • Socket(String host, int port, InetAddress localAddr, int localPort) – This connects the socket to the host mentioned in the constructor.

Important Methods in Socket Class in Java

  1. public InputStream getInputStream() – Serves the purpose of returning the InputStream bound with the socket.
  2. public OutputStream getOutPutStream() – This serves the purpose of returning the Output Steam attached to the socket.
  3. public synchronized void close() – As the name suggests, this closes the connection.
  4. public InputStream getInputStream() – This method returns the InputStream of the socket in action. This stream is in connection with the OutputStream of the other remote socket.
  5. publicOutputStream getOutputStream() – This method returns the OutputStream of the socket. As you might think, the OutputStream is connected with the InputStream of the remote socket.

There are plenty of other methods too in the Socket class. Make sure to check out the documentation for that.

Although we all know no developer has ever done that.

ServerSocket Class in Java

Serversocket class method in Java

This class proves to be useful when you create a socket. It has several methods for doing that. Each socket waits for some requests to come over the network.

As soon as it receives a request, it performs the required operations and sends back the response.

However, do note that the actual weight lifting of the sockets is performed by the “SocketImpl” class.

Important Methods of the ServerSocket Class

  1. public socket accept( ) – This returns the socket object and establishes a connection between the client and the server.
  2. public synchronized void close() – As the name suggests, this closes the connection.
  3. public int getLocalPort() – When you ask the server to choose any port, then this method is useful for returning the port on which the server is running.

InetAddress Class Methods in Java

 

This class is solely dedicated to IP Addresses. There are a few methods we need to learn about.

  1. static InetAddress getByAddress(byte[]addr) – This returns the InetAddress of the raw IP address given.
  2. static InetAddress getByAddress(String host, byte[]addr) – This returns the InetAddress when the hostname and the IP address is given.
  3. String getHostAddress() – This returns the IP address in a String format.

Let us look at a simple client-server connection through a Java Socket Program.

Java Program to Illustrate the use of Socket Programming in Java

At first, we will design the server-side logic.

Server.java:

package com.dataflair.socketinjava;

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

public class Server {
   
    public static void main(String[] args) {
        System.out.println("Starting the Server!! Any errors will be reported on the screen.... ");
        try {
            ServerSocket s = new ServerSocket(8080);
            //This creates a new socket at port 8080. 
            Socket sock=s.accept();
            DataInputStream dis = new DataInputStream(sock.getInputStream());
            String sockmsg =  (String)dis.readUTF();
            System.out.println("The message received is "+sockmsg);
            //This simply prints whatever message the server receives from the client.
            //Now we close the socket
            s.close();
            //
        } catch (Exception e) {
            //TODO: handle exception
            System.out.println("There was an error with the file.");
    
        }
    }
    

    
}

The Client Code:

package com.dataflair.socketinjava;
import java.net.*;
import java.io.*;


public class Client 
{


    public static void main(String[] args) {
        try {
            //At first we create a socket
            Socket clientsock=new Socket("localhost",8080);
            DataOutputStream out = new DataOutputStream(clientsock.getOutputStream());
            out.writeUTF("Hey this is a client message!");
            out.flush();
            out.close();
            clientsock.close();


        } catch (Exception e) {
            //TODO: handle exception
            System.out.println("There is an error in the system!");
            System.out.println(e.getMessage());
            
        }      
    }
}

OUTPUT for both the programs:

Socket Programming in Java

Now you must be thinking that it is not very efficient of an approach if I can only send a single message at a time. A duplex communication is essential.

Let us create one!

First, we will create the Server program! This will be similar to the previous program.

Server.java:

package com.dataflair.socketinjava;

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

public class Server {
   
    public static void main(String[] args) {
        try
        {
            System.out.println("Starting the Server!! Any errors will be reported on the screen.... ");
            ServerSocket s = new ServerSocket(8080);
            //This creates a new socket at port 8080. 
            Socket sock=s.accept();
            DataInputStream din = new DataInputStream(sock.getInputStream());
            DataOutputStream dout = new DataOutputStream(sock.getOutputStream());
            Scanner sc = new Scanner(System.in);
            String mesgreceive="", mesgsent="";
            
            while(true)
            {
                
                mesgreceive=din.readUTF();
                System.out.println("Client Message:"+mesgreceive);
                System.out.println("Please enter your message");
                mesgsent=sc.nextLine();
                dout.writeUTF(mesgsent);
                dout.flush();
                if(mesgsent.equals("kill")||mesgreceive.equals("kill"))
                break;
                
                
            }
            din.close();
            dout.close();

            System.out.println("Closing the connection socket!");
            s.close();
    }
    catch(Exception e)
    {
        System.out.println("There was an error in the program! " + e.getMessage());
    }
}
}

Client.java:

package com.dataflair.socketinjava;
import java.net.*;
import java.io.*;
import java.util.*;


public class Client 
{


    public static void main(String[] args) {
        try {
            //At first we create a socket
            Socket clientsock=new Socket("localhost",8080);
            DataOutputStream out = new DataOutputStream(clientsock.getOutputStream());
            DataInputStream in =new DataInputStream(clientsock.getInputStream());
            String receivemsg="",sendmesg="";
            Scanner sc = new Scanner(System.in);

            out.writeUTF("Hey this is a client message!");
            out.flush();
            while(true)
            {
                //For this case, we will be sending a message from the client to the server first. 
                //We don’t want to be stuck with a deadlock now. 
                receivemsg=in.readUTF();
                System.out.println("Server Says: "+receivemsg);
                System.out.println("Please enter your message");
                sendmesg=sc.nextLine();

                out.writeUTF(sendmesg);
                out.flush();
                if(receivemsg.equals("kill")||sendmesg.equals("kill"))
                {
                    System.out.println("Someone broke the conversation!");
                    break;
                }


            }
            sc.close();
            out.close();
            in.close();
            
            clientsock.close();


        } catch (Exception e) {
            //TODO: handle exception
            System.out.println("There is an error in the system!");
            System.out.println(e.getMessage());

        }      
    }
}

Now when we start the program we see that the Client messages the server. This is to start a basic conversation.

If both the client and the server waited for a hello message, it would have been difficult to proceed with the connection.

Now let us look at the conversation we had in between the Client and the Server.

Java socket programming

This is beautiful. The possibilities are endless on what we can do with this.

Go on, put on your explorer hats and wreak havoc!

Summary

Socket programming is just scratching the surface!

We can do a plethora of things with sockets and Java.

We learned about the Socket Class, Server Socket class, how to do one-way connections and duplex connections as well!

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google | Facebook

2 Responses

  1. kiran sahu says:

    Great article! These traits really makes programming language good and unique. I am glad to read your article as java beginner as its good to know about these characteristics. Thanks a lot for sharing!

    • DataFlair Team says:

      We are glad that our readers are liking DataFlair Java Tutorial series. Stay with DataFlair for more such interesting articles and keep yourself updated with technologies.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.