In the following example, multithreading is used.
Import Java.io.bufferedreader;import Java.io.bufferedwriter;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstreamwriter;import Java.io.printwriter;import Java.net.serversocket;import Java.net.socket;class Serveronejabber extends Thread {private Socket socket;private BufferedReader in;private printwriter out;public serveronejabber (socket s) throws IOException {socket = S;in = new Buffere Dreader (New InputStreamReader (Socket.getinputstream ()));//Auto Flushout = new PrintWriter (new OutputStreamWriter (Socket.getoutputstream ())), true); start ();} public void Run () {try {while (true) {String str = in.readline (); if (Str.equals ("END")] break; System.out.println ("Ecoh:" + str); out.println (str);} System.out.println ("closing");;} catch (IOException e) {//Todo:handle exception} finally {try {socket.close ()} catch (IOException E2) {//Todo:handle E Xception}}}}public class Multijabberserver {static final int PORT = 8080;public static void Main (StriNg args[]) throws IOException {ServerSocket s = new ServerSocket (PORT); SYSTEM.OUT.PRINTLN ("server start"); try {while (true) {Socket socket = s.accept (); try {new serveronejabber (socket);} catch (IOException e) {socket.close ();}}} finally {s.close ();}}}
Then the client
Import Java.io.bufferedreader;import Java.io.bufferedwriter;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstreamwriter;import Java.io.printwriter;import Java.net.inetaddress;import Java.net.socket;import Java.security.cert.trustanchor;class JabberClientThread extends Thread{private final int PORT =8080;p rivate socket socket;p rivate bufferedreader in;p rivate printwriter out;p Rivate St atic int counter =0;private int ID =counter++;p rivate static int threadcount =0;public static int threadcount () {return T Hreadcount;} Public Jabberclientthread (inetaddress addr) {System.out.println ("Making Client ID:" + ID); ThreadCount + +; try {socket = n EW Socket (addr,port);} catch (IOException e) {//Todo:handle exception}try {in = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); out = new PrintWriter (new BufferedWriter (New OutputStreamWriter (Socket.getoutputstream ())), true);} catch (Exception e) {try {socket.close ();} catch (Exception E2){//Todo:handle exception}}} public void Run () {try {for (int i =0; i<25;i++) {OUT.PRINTLN ("Client ID:" +i); String str = in.readline (); System.out.println (str);} Out.println ("END");} catch (Exception e) {//Todo:handle Exception}finally{try {socket.close ();} catch (IOException E2) {ThreadCount--;//end This thread}}}}public class Multijabberclient {static final int max_thread =40;public static void Main (String args []) Throws IOException, interruptedexception{inetaddress addr = Inetaddress.getbyname (null), while (true) {if ( Jabberclientthread.threadcount () <max_thread) {new Jabberclientthread (addr);}}}
Network programming server