Friday, 6 February 2015

Socket Programming with Multiple Thread

JSERVER.JAVA import java.io.*; import java.net.*; class JServer { public static void main(String[] args) { try{ ServerSocket ss=new ServerSocket(5700); while(true){ Socket cs=ss.accept(); Worker w=new Worker(cs); Thread t1=new Thread(w); t1.start(); } } catch(Exception e) {System.out.println(e.getMessage());} } } WORKER.JAVA import java.io.*; import java.net.*; class Worker implements Runnable { Socket s; Worker(Socket s) { this.s=s; } public void run() { try{ InputStreamReader isr=new InputStreamReader(s.getInputStream()); OutputStreamWriter osw=new OutputStreamWriter(s.getOutputStream()); BufferedReader br=new BufferedReader(isr); BufferedWriter bw=new BufferedWriter(osw); while(true){ String input=br.readLine(); bw.write("KMIT"+input); bw.newLine(); bw.flush(); } }catch(Exception e) {System.out.println(e.getMessage());} } } JCLIENT.JAVA import java.io.*; import java.net.*; class JClient { public static void main(String[] args) { try{ Socket s=new Socket("localhost",5700); InputStreamReader isr=new InputStreamReader(s.getInputStream()); OutputStreamWriter osw=new OutputStreamWriter(s.getOutputStream()); BufferedReader br=new BufferedReader(isr); BufferedWriter bw=new BufferedWriter(osw); while(true) { bw.write("HYDERABAD"); bw.newLine(); bw.flush(); String output=br.readLine(); System.out.println(output); } } catch(Exception e) {System.out.println(e.getMessage());} } }

No comments:

Post a Comment