Socket Programming in Java – Established Java Socket Connection 1


1. Java Socket Tutorial – Objective

In our last Java tutorial, we discussed the Java URL Class. Here, in this Java Socket Tutorial, we are going to learn what is Socket programming in Java and how to use Java Socket Programming. Moreover, we will discuss an implementation of Socket Programming and Establish Java Socket Connection.

So, let’s Start Socket Programming in Java.

Socket Programming in Java

Socket Programming in Java – Established Java Socket Connection

2. What is Socket Programming in Java

Socket Programming in Java depicts an exceptionally fundamental one-way Client and Server setup where a Client associates, sends messages to a server and the server indicates them utilizing attachment association. There’s a ton of low-level stuff that necessities to occur for these things to work yet the Java API organizing package (java.net) deals with the majority of that, making system programming simple for software engineers.

Do you know about Java Exception

a. Java Client Side Programming

How to Establish a Java Socket Connection

To associate with other machines we require an attachment association. An attachment association implies the two machines have data about each other’s system area (IP Address) and TCP port. The java.net.Socket class speaks to a Socket. To open an attachment:

Syntax –

Attachment = new Socket("127.0.0.1", 5000)
  • To start with contention – IP address of Server. (127.0.0.1 is the IP address of localhost, where the code will keep running on the single remain solitary machine).
  • Second contention – TCP Port. (Only a number speaking to which application to keep running on a server. For instance, HTTP keeps running on port 80. Port number can be from 0 to 65535.

Let’s Explore Pair Class in Java With Techniques

Note- For communication, streams are used for both input and output.

Java socket connection is closed once the message has been sent.

b. Implementation of Socket Programming in Java

Following is the Example of Java Socket Programming:

import java.net.*;
import java.io.*;
public class Client
{
    private Socket socket            = null;
    private DataInputStream  input   = null;
    private DataOutputStream out     = null;
// constructor to put ip address and port
    public Client(String address, int port)
        {
           try
             {
                socket = new Socket(address, port);
                System.out.println("Connected");
                input  = new DataInputStream(System.in);
                out    = new DataOutputStream(socket.getOutputStream());
             }
        catch(UnknownHostException u)
          {
             System.out.println(u);
          }
        catch(IOException i)
          {
            System.out.println(i);
          }
        String line = "";
        while (!line.equals("Over"))
          {
             try
               {
                  line = input.readLine();
                  out.writeUTF(line);
               }
             catch(IOException i)
              {
                 System.out.println(i);
              }
         }
        try
        {
            input.lose();
            out.close();
            socket.close();
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
    }

    public static void mainString args[])
    {
        Client client = new Client("127.0.0.1", 5000);
    }
}

Read about Declaration and Calling a Java Method

c. Server Programming – Establish a Java Socket Connection

Two sockets are needed to write a server application, viz.

  • ServerSocket – IT waits for client requests
  • A plain old socket – Used for communication.

getOutputStream() method is used for communication, for sending outputs.

Example –

import java.net.*;
import java.io.*;
public class Server
{
    private Socket socket   = null;
    private ServerSocket server   = null;
    private DataInputStream in       =  null;
    public Server(int port)
    {
        try
        {
            server = new ServerSocket(port);
            System.out.println("Server started");
            System.out.println("Waiting for a client ...");
            socket = server.accept();
            System.out.println("Client accepted");
            in = new DataInputStream(
            new BufferedInputStream(socket.getInputStream()));
            String line = "";
            while (!line.equals("Over"))
            {
                try
               {
                    line = in.readUTF();
                   System.out.println(line);
                }
                catch(IOException i)
                {
                    System.out.println(i);
                }
            }
            System.out.println("Closing connection");
           socket.close();
            in.close();
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
    }
public static void main(String args[])
    {
        Server server = new Server(5000);
    }
}

Important Points

  • Server application makes a ServerSocket on a particular port which is 5000. This begins our Server tuning in for customer demands coming in for port 5000.
  • At that point, Server makes another Socket to speak with the customer.

Do You Know Difference Between Abstract Class and Interface in Java

Syntax –

attachment = server.accept()
  • The acknowledge() strategy blocks(just stays there) until the point when a customer associated with the server.
  • At that point, we take a contribution from the attachment utilizing getInputStream() technique. Our Server continues accepting messages until the point when the Client sends “Over”.
  • After we’re done we close the association by shutting the attachment and the information stream.
  • To run the Client and Server application on your machine, gather them two. At that point first, run the server application and afterward run the Client application.

This was all about Socket Programming in Java Tutorial. Hope you like our explanation.

Let’s read about Multithreading in Java 

3. Conclusion

Hence, in this Java Socket tutorial, we learned about What is socket programming in Java, how to implement Java Socket Connection with steps and Java Socket Client examples. Furthermore, if you have any query feel free to ask in a comment section.

Related Topic- Constructor in Java 

For reference 


One thought on “Socket Programming in Java – Established Java Socket Connection

  • kiran sahu

    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!

Comments are closed.