Today I learned how to implement socket communication in Java, the difficulty is on the IO, because Java is already perfect for socket encapsulation.
Today the code spent the whole night debugging, the main reason is the flush problem of IO and command line how to run the class with the package, but finally the problem is basically solved, put the code for your reference
Server
Public classTCPServer { Public Static voidMain (string[] args)throwsException {serversocket server=NewServerSocket (9091); Try{Socket Client=server.accept (); Try{BufferedReader input=NewBufferedReader (NewInputStreamReader (Client.getinputstream ())); BooleanFlag =true; intCount = 1; while(flag) {SYSTEM.OUT.PRINTLN (the client is going to start to flirt, this is the first+ Count +times! ); Count++; String Line=Input.readline (); SYSTEM.OUT.PRINTLN (client says:+Line ); if(Line.equals (exit)) {flag=false; SYSTEM.OUT.PRINTLN (the client does not want to play!) ); } Else{System.out.println (client says:+Line ); } } } finally{client.close (); } } finally{server.close (); } }}Client
Public classTcpClient { Public Static voidMain (string[] args)throwsException {Socket client=NewSocket (127.0.0.1, 9091); Try{printwriter output=NewPrintWriter (Client.getoutputstream (),true); Scanner Cin=NewScanner (system.in); String words; while(Cin.hasnext ()) {words=Cin.nextline (); OUTPUT.PRINTLN (words); System.out.println (writes out the data:+words); } cin.close (); } finally{client.close (); } }}
Java for simple socket communication