Requirements: Establish client and server side, the client from the keyboard input string to the server side, the server returns the uppercase form of the string to the client.
Before I start writing code, I'm going to give you a refresher on the flush () method of the buffers in the IO stream. For example, the service sends data to the client, in order to transfer data efficiently, there will be a buffer in the output stream, and only when the buffer is filled, the buffer will send the data to the client and, if not filled, waits to be filled. But what if the data we're transmitting just can't fill the buffer? This shows the importance of the flush () method, which forces the transfer of data from the buffer to the destination.
1. Client
ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.OutputStreamWriter;ImportJava.io.PrintWriter;ImportJava.net.Socket;Importjava.net.UnknownHostException; Public classClient { Public Static voidMain (string[] args)throwsunknownhostexception, IOException {System.out.print ("Client-initiated"); Socket s=NewSocket ("10.192.9.100", 10006); //Create a read stream from a keyboard entryBufferedReader bufr=NewBufferedReader (NewInputStreamReader (system.in)); //Create an output stream from memory to the socket streamBufferedWriter out=NewBufferedWriter (NewOutputStreamWriter (S.getoutputstream ())); //Create a read stream from the socket to the memoryBufferedReader bufin=NewBufferedReader (NewInputStreamReader (S.getinputstream ())); String Line=NULL; while((Line=bufr.readline ())! =NULL) { if(Line.equals ("Over")) Break; //if there is no \ r \ n, the ReadLine () in the server-side while will wait for the newline without the following programOut.write (line+ "\ r \ n"); //if not refreshed, no data is sent because the buffer is not filledOut.flush (); String Upperstr=Bufin.readline (); System.out.print (UPPERSTR); } s.close (); }}
2. Service-side
Because the attention in the service side is the same as the client, it is no longer annotated
ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter;ImportJava.io.PrintWriter;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classServer { Public Static voidMain (string[] args)throwsIOException {System.out.print ("Server-side startup"); ServerSocket SS=NewServerSocket (10006); Socket s=ss.accept (); BufferedReader Bufin=NewBufferedReader (NewInputStreamReader (S.getinputstream ())); //PrintWriter out = new PrintWriter (S.getoutputstream (), true);BufferedWriter out=NewBufferedWriter (NewOutputStreamWriter (S.getoutputstream ())); String Line=NULL; while((Line=bufin.readline ())! =NULL) {System.out.print (line); Out.write (Line.touppercase ()+ "\ r \ n"); Out.flush (); } s.close (); Ss.close (); } }
Client server-side interaction (TCP) Java