Sockets programming in Java for Client/Server



Note:

Establishing Communication between a Server and a Client through a socket is called Socket Programming

  • To create the Client Socket Socket Class is available in java.net package.
  • To create ServerSocket, ServerSocket class is avialable in java.net package
  • A Client is a machine that sends a request for some service
  • A Server is machine that provides services to the client


Note:  Write a java program to create a client and server Communication between them

// A Server that sends a String to the client as a response to the client connection

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

class Server1
{
public static void main(String args[])throws IOException
{

//create the serversocket

ServerSocket ss=new ServerSocket(777);

//make the socket to accept the client connection

Socket s=ss.accept();
System.out.println(“connection established”);

//flow of data in the socket

OutputStream obj=s.getOutputStream();

//to send data to the client

PrintStream ps=new PrintStream(obj);

//to receive data from the client

BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));

//to read data from keyboard

BufferedReader kb=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String str,str1;
while((str=br.readLine())!=null)
{
System.out.println(str);
str1=kb.readLine();
ps.println(str1);
}

//disconnet server

ss.close();
s.close();
br.close();
kb.close();
ps.close();
System.exit(0);
}
}
}

// A Client that sends a Request to the Server for the response

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

class Client1
{
public static void main(String args[])throws IOException
{

//create client socket

Socket s=new Socket(“localhost”,777);

//data send by the client the dos is most preferable

DataOutputStream dos=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in));
String str,str1;
while(!(str=kb.readLine()).equals(“exit”))
{
dos.writeBytes(str+”\n”);
str1=br.readLine();
System.out.println(str1);
}

//disconnect the client

dos.close();
br.close();
kb.close();
}
}

Procedure of Compiling  and executing the program

  1. First Compile the Client Program and wait for the server compilation javac Client1.java
  2. Secound Compile the Server Program and wait for the client compilation javac Server1.java
  3. and Run the server wait for the request from the client  java Server1.
  4. But don’t run the Server program before the Compilation of the Client compilation
  5. Run the Client and send the Request to the Server which is waiting for the connection to be establish by java Client1.
  6. After the client sends the request the server will show the message as the Connection is established and ready for the communication.


Share with SociBook.com

Random Posts

Post a Comment