1. First we build the server-side code , as follows:
1 Packagecn.itcast_07;2 3 Importjava.io.IOException;4 ImportJava.io.InputStream;5 ImportJava.io.OutputStream;6 ImportJava.net.ServerSocket;7 ImportJava.net.Socket;8 9 Public classServerdemo {Ten Public Static voidMain (string[] args)throwsIOException { One //Create a Server socket object AServerSocket SS =NewServerSocket (9999); - - //Listening for client connections theSocket s = ss.accept ();//Blocking - - //Get input stream -InputStream is =S.getinputstream (); + byte[] Bys =New byte[1024]; - intLen = Is.read (bys);//Blocking +String Server =NewString (bys, 0, Len); ASYSTEM.OUT.PRINTLN ("Server:" +server); at - //Get output stream -OutputStream OS =S.getoutputstream (); -Os.write ("Data has been received". GetBytes ()); - - //Freeing Resources in s.close (); - //ss.close (); to } +}
2. Build the client code as follows:
1 Packagecn.itcast_07;2 3 Importjava.io.IOException;4 ImportJava.io.InputStream;5 ImportJava.io.OutputStream;6 ImportJava.net.Socket;7 8 Public classClientdemo {9 Public Static voidMain (string[] args)throwsIOException {Ten //creating a Client socket object OneSocket s =NewSocket ("192.168.12.92", 9999); A - //Get output stream -OutputStream OS =S.getoutputstream (); theOs.write ("Nice day, good for Sleep". GetBytes ()); - - //Get input stream -InputStream is =S.getinputstream (); + byte[] Bys =New byte[1024]; - intLen = Is.read (bys);//Blocking +String client =NewString (bys, 0, Len); ASYSTEM.OUT.PRINTLN ("Client:" +client); at - //Freeing Resources - s.close (); - } -}
Open the server side first, as follows:
re-open the client , as follows:
This time we look back at the server side, as follows:
Java Basic Knowledge Enhancement Network programming note 07:TCP Server to the client a feedback case