This program is helpful in the implementation where we want a machine works as a client for other machines and same machine works as a server for other machines. This technique for example useful in ring topology, star topology program implementation in networking
package DemoSocket; import java.io.*; import java.net.*; import java.util.Scanner; class ServerThread extends Thread // Server Program { ServerThread() { this.start(); } public void run() { try { ServerSocket serv=new ServerSocket(8084); Socket client=serv.accept(); ObjectInputStream in=new ObjectInputStream(client.getInputStream()); String request=in.readObject().toString(); char arr[]=request.toCharArray(),tmp; int len=request.length(); int i=0,j=len-1; while(i<j) { tmp=arr[i]; arr[i]=arr[j]; arr[j]=tmp; i++; j--; } String response=new String(arr); ObjectOutputStream out=new ObjectOutputStream(client.getOutputStream()); out.writeObject(response); } catch(Exception ex) { ex.printStackTrace(); System.out.println("ServerSide Error :"+ex); } } } class ClientThread extends Thread // Client Program { ClientThread() { this.start(); } public void run() { try { Scanner sc=new Scanner(System.in); System.out.print("Enter any string :"); String input=sc.next(); InetAddress inet=InetAddress.getByName("127.0.0.1"); Socket client=new Socket(inet,8084); ObjectOutputStream out=new ObjectOutputStream(client.getOutputStream()); out.writeObject(input); ObjectInputStream in=new ObjectInputStream(client.getInputStream()); String rev=in.readObject().toString(); System.out.println("Reverse of the String :"+rev); } catch(Exception ex) { System.out.println("ClientSide Error :"+ex); } } } public class SameCS // Main Program { public static void main(String args[]) { new ServerThread(); new ClientThread(); } }
No comments:
Post a Comment