Java Socket Programming (part 2)

In this Blog we will Learn : –

  • Server Socket Class
  • Socket Class
  • Creation of Server and Client

ServerSocket Class 

The java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests

Socket Class

The java.net.Socket class represents the socket that both the client and server use to communicate with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method.

For a Brief Description of Socket class and ServerSocket Class is Click here.

Creation of Server and Client

Server.java file

import java.net.*;
import java.io.*;
public class Server
{
 public static void main(String args[])
 {
 try
 {
 ServerSocket s = new ServerSocket(9001);
 System.out.println("Waiting for a connection");
 Socket s1=s.accept();
 System.out.println("Connected to client ");
 DataInputStream din = new DataInputStream(s1.getInputStream());
 DataOutputStream dout = new DataOutputStream(s1.getOutputStream());
 String str=(String)din.readUTF(); 
 System.out.println("message= "+str); 
 dout.writeUTF("Hello Client");
 s.close(); 
 }catch(Exception e)
 {
 System.out.println(e);
 } 
 }
}

Client.java

import java.net.*;
import java.io.*;
public class Client
{
 public static void main(String args[])
 {
 try
 {
 Socket s1=new Socket("localhost",9001);
 System.out.println("Just connected to " + s1.getRemoteSocketAddress());
 int port =s1.getPort();
 int local_port=s1.getLocalPort();
 System.out.println("Connected to server on port No."+port+" with local port"+local_port);
 DataInputStream din=new DataInputStream(s1.getInputStream());
 DataOutputStream dout=new DataOutputStream(s1.getOutputStream()); 
 //public InputStream getInputStream() : - Returns the input stream of the socket. The input stream is connected to the output stream of the remote socket.
 dout.writeUTF("Hello Server");
 String str=(String)din.readUTF(); 
 System.out.println("message= "+str); 
 dout.flush(); 
 dout.close(); 
 s1.close(); 
 }
 catch(Exception e)
 {
 System.out.println(e);
 } 
 }
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s