Business scenario: There is now a socket server to send us the data we need to create a socket Client to connect to the socket Server, and then accept the data sent from the server. But the server may be interrupted, so the Client to have a while to keep an infinite loop connected to the Server.
Package com.thinkgem.wlw.modules.test.socketdemo; Import the java.io. * ; Import the java.net.Socket; Import a java.net.UnknownHostException; Import java.util.Scanner; / ** * @author zhouhe * @ 2019/10/14 17:41 DATE * / public class Client the extends the Thread { // definition of a Socket object Socket Socket = null ; public Client (Host String, int port) { the try { // requires an IP address and port number of the server in order to obtain the correct target Socket socket = new newThe Socket (Host, Port); } the catch (UnknownHostException E) { e.printStackTrace (); } the catch (IOException E) { e.printStackTrace (); } } @Override public void RUN () { // the client is connected to a can write the data servers new new sendMessThread () Start ();. Super .run (); the try { // read Sock data inside the InputStream S = Socket.getInputStream (); byte [] = buf new new byte [1024]; Int len = 0 ; the while (! (Len = s.read (buf)) = -1 ) { System.out.println ( new new String (buf, 0 , len)); } } the catch (IOException E) { e.printStackTrace (); } } // to write data inside Socket need to open a new thread class sendMessThread the extends the thread { @Override public void RUN () { Super .run (); // write Scanner Scanner = null ; OutputStream os= null; try { scanner=new Scanner(System.in); os= socket.getOutputStream(); String in=""; do { in=scanner.next(); os.write((""+in).getBytes()); os.flush(); } while (!in.equals("bye")); } catch (IOException e) { e.printStackTrace (); } scanner.close (); the try { os.close (); } the catch (IOException E) { e.printStackTrace (); } } } // function entry public static void main (String [] args ) { // need to correct server IP address and port number of the while ( to true ) { Client ClientTest = new new Client ( "192.168.0.109", 777 ); clientTest.start (); } } }
If you can not find here socket Server, it will complain, once the socket Server is found, it will automatically connect, send and receive data over the server