1, the following is just a simple example, there is no multithreading, only one (because the scan.nextline () thread will enter the waiting state), use can be based on the specific project function to optimize processing
2, the following code uses 1.8 new features, if you want to test the following code, Java version can not be less than 1.8
//Client Public Static voidMain (string[] args) {Try(Scanner scan =NewScanner (system.in); Socket Client=NewSocket ("127.0.0.1", 8484); PrintWriter writer=NewPrintWriter (Client.getoutputstream ()); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (Client.getinputstream ()));) { while(true) { //Writer.print (Scan.nextline () + "\ n"); //Writer's Write (Scan.nextline () + "\ n") method//Note: Because the server side is using ReadLine, if it is written in the above two ways, you must add a newline character, otherwise readline is not read the datawriter.println (Scan.nextline ()); Writer.flush (); while(Reader.ready ()) {System.out.println (Reader.readline ()); } } } Catch(IOException e) {e.printstacktrace (); } }
//Service Side Public Static voidMain (string[] args) {Try(Scanner scan =NewScanner (system.in); ServerSocket Server=NewServerSocket (8484); Socket SC=server.accept (); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (Sc.getinputstream ())); PrintWriter writer=NewPrintWriter (Sc.getoutputstream ());) { while(true) {writer.println (Scan.nextline ()); Writer.flush (); while(Reader.ready ()) {System.out.println (Reader.readline ()); } } } Catch(Exception e) {e.printstacktrace (); } }
Java socket Programming Development Simple example