Server.java
Import Java.io.*;import java.net.*;p ublic class Server {public static final int port=8888; public void Server () throws IOException {ServerSocket ss = new ServerSocket (PORT); InetAddress ia = inetaddress.getbyname (null); System.out.println ("[email protected]" +ia+ "start!"); try{while (true) {Socket s = ss.accept ();//Listen PORT; try{new ServerOne (s); } catch (IOException e) {s.close (); }}}finally{Ss.close (); System.out.println ("Server stop!"); }}}class ServerOne extends Thread {private Socket s; Private BufferedReader in; Private PrintWriter out; Public ServerOne (Socket s) throws IOException {this.s = s; in = new BufferedReader (New InputStreamReader (S.getinputstream ())); out = new PrintWriter (new BufferedWriter (New OUTPUTSTREAMWRiter (S.getoutputstream ())), true); Start (); public void Run () {try {while (true) {String str = in.readline (); if (Str.equals ("End")) break; SYSTEM.OUT.PRINTLN ("server:receive Information" +str); Out.println ("Echo:" +str); } System.out.println ("Closing ..."); } catch (IOException e) {} finally {try{s.close (); }catch (IOException e) {}}}}
Client.java:
Import Java.io.*;import java.net.*;p ublic class Client extends Thread {static final int max_threads=25; private static int id = 0; private static int threadcount = 0; Private Socket S; Private BufferedReader in; Private PrintWriter out; public static int Getthreadcount () {return threadcount; } public Client (InetAddress ia) {threadcount++; id++; SYSTEM.OUT.PRINTLN ("Making client:" + ID); try{s = new Socket (IA, server.port); } catch (IOException e) {} try{in = new BufferedReader (New InputStreamReader (S.getinputstream ())); out = new PrintWriter (new BufferedWriter (New OutputStreamWriter (S.getoutputstream ())), true); Start (); }catch (IOException E1) {try{s.close (); }catch (IOException E2) {System.out.println ("Error in client\n"); }}} public void Run () {try{ String str; for (int i = 0; i < 5; i++) {out.println ("Client #" +id+ ":" +i); Str=in.readline (); System.out.println ("Client:send message#" +id+ ":" +i+ "\ n" + "Server reply:" +str); } out.println ("End"); }catch (IOException e) {}finally{try {s.close (); } catch (IOException e) {}}} public static void Main (String args[]) throws IOException, Interruptedexception {InetAddress ia = inetaddress.getbyname (null);//null mean localhost while (true) {if (GETTHREADC Ount () < max_threads) New Client (IA); else break; Thread.CurrentThread (). Sleep (10); } }}
Implementing Server and Client (TCP) using Java