How do we create and use sockets in Java?

How do we create and use sockets in Java?

A socket is a software endpoint that establishes communication between a server program and one or more client programs. The socket associates the server program with a specific hardware port on the machine where it runs so any client program anywhere in the network with a socket associated with that same port can communicate with the server program. In Java, TCP/IP socket connections are implemented with classes in java.net package. The programming is done on both server side and client side.TCP/IP server applications rely on the ServerSocket and Socket networking classes.

Example of TCP/IP server application:

import java.net.*;
import java.io.*;
public class SimpleServer
{
  public static void main (String args[ ])
  {
    ServerSocket s= null;
  try
  {
    s=new ServerSocket (5432);
  }
  catch (IOException e)
  {
    e.printStackTrace();
  }
//Run the listen/accept loop forever
while (true)
  {
    try
    {
       Socket s1= s.accept();
       OutputStream sout= s1.getOutputStream ();
       BufferedWriter b= new BufferedWriter (new OutputStreamWriter (sout));
       b.write(“Hello”);
       b.close ();
       s1.close ();
    }
catch (IOException e)
   {
     e.printStackTrace();
   }
  }
 }
}

The client side of a TCP/IP application relies on the Socket class.

import java.net.*;
import java.io.*;
public class SimpleClient
{
   public static void main (String args[ ])
     {
       try
         {
            Socket s1=new Socket ( “127.0.0.1”, 5432);
            InputtStream is= s1.getInputStream ();
            DataInputStream dis =new DataInputStream (is);
            System.out.println(dis.readUTF());
            br.close();
            s1.close ();
         }
catch (ConnectionException c)
    {
        System.out.println( c);
    }
catch (IOException e)
    {
        e.printStackTrace ();
    }
   }
  }
}
Send data from a Java program to CGI program
There are two methods of sending data from Java program to a CGI Program: a.) The first method is that we can use CGI scripting on both client and server by using...
Purpose of the executable files
Java - purpose of the executable files - java_g is a non-optimized version of java suitable for use with debuggers like jdb. When using java_g to run a program that loads a shared library...
URL instance vs. URLConnection instance
URLConnection is a class under java.net package. The abstract class URLConnection is the superclass of all classes that represent...
Post your comment