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 ();
}
}
}
}