JAVA 62nd-TCP protocol exercises

Source: Internet
Author: User

JAVA 62nd-TCP protocol exercises

Understanding TCP transmission problems through practice


Exercise 1:Create an English capital conversion Server

The client enters a Letter of data and sends it to the server. After receiving the data, the server displays the data in the console and converts the data to uppercase and returns it to the client. If the client inputs over, the conversion ends.

Public class Main {public static void main (String [] args) throws IOException {Text_Transform_Client (); Text_Transform_Server ();} public static void Text_Transform_Server () throws IOException {// convert text to server/* convert server * 1. create a ServerSocket Server Object * 2. obtain the Socket object * 3. source: Socket, read the data sent from the client to be converted * 4. sink: displayed on the console * 5. convert data to uppercase and return the client * // create the Server Object ServerSocket ss = new ServerSocket (6534); // obtain the socket object Socket socket = ss. accept (); // get I P. identify who is connected to String ip = socket. getInetAddress (). getHostAddress (); System. out. println ("ip:" + ip); // get the socket to read the stream and decorate BufferedReader br = new BufferedReader (new InputStreamReader (socket. getInputStream (); // get the socket output stream and decorate PrintWriter pw = new PrintWriter (socket. getOutputStream (), true); // new PrintWriter (socket. outputtream () String line = null; while (line = br. readLine ())! = Null) {System. out. println (line); pw. println (line. toUpperCase (); // pw. print (line. tpUpperCase + "\ r \ n");} // pw. flush (); socket. close (); ss. close ();} public static void Text_Transform_Client () throws IOException {// text conversion client/** conversion client: * 1. create a Socket Client object * 2. obtain keyboard input * 3. sends the entered information to the Socket output stream */Socket socket = new Socket ("127.0.0.1", 6534); BufferedReader br = new BufferedReader (new InputStreamReader (System. in); // The Source is: Keyboard, sink: Socket output stream // new BufferedWriter (new OutputStreamWriter (socket. getOutputStream (); PrintWriter pw = new PrintWriter (socket. getOutputStream (), true); // new PrintWriter (socket. getOutstream (); // Socket input stream, read the upper-case data returned by the server BufferedReader br2 = new BufferedReader (new InputStreamReader (socket. getInputStream (); String line = null; while (line = br. readLine ())! = Null) {if ("over ". equals (line) break; pw. println (line); // pw. print (line + "\ r \ n") // pw. flush (); // read the String str = br2.readLine (); System. out. println ("up:" + str);} socket. close ();}}

FAQs:

1. The above code has a problem: after the client inputs over, the client ends. Is the server end?

The readline () method is a blocking method, but after the client inputs over, the client socket closes and returns a-1. The read method in the readline () method of the server reads-1, therefore, the readline () method reads null and ends.


2. If the PrintWriter pw = new PrintWriter (socket. getOutputStream () on the client and server is automatically refreshed and removed, what will happen if the automatic line feed of pw. print () is removed?

The client does not receive the converted data and the server does not display the data.

Because the data written by pw. print () on the client is written to PrintWriter and not refreshed to the socket input stream.

PS: this is the situation where both ends of TCP are waiting during transmission. It is likely that the data is not sent, and the most likely is the blocking method.

Of course, it can be found in pw. print (); add pw. flush (), but the problem persists, because the readline read end mark is a line break, so the pw. print (+ "\ r \ n"), so to solve the problem, you must add the refresh action and line break to both the client and the server.

Once the above problem is encountered, it is generally because the server and client are waiting because of the blocking method. Therefore, it is better to follow the code example above.


Exercise 2: Upload a text file

Public class Main {public static void main (String [] args) throws IOException {UpText_Client (); UpText_Server ();} public static void UpText_Server () throws IOException {ServerSocket ss = new ServerSocket (6534); Socket socket = ss. accept (); BufferedReader br = new BufferedReader (new InputStreamReader (socket. getInputStream (); BufferedWriter bw = new BufferedWriter (new FileWriter ("c: \ server.txt"); String l Ine = null; while (line = br. readLine ())! = Null) {// if ("over ". equals (line) break; // * bw. write (line); bw. newLine (); // * bw. flush (); // *} PrintWriter pw = new PrintWriter (socket. getOutputStream (), true); pw. println ("uploaded successfully"); br. close (); bw. close (); socket. close (); ss. close ();} public static void UpText_Client () throws IOException {Socket socket = new Socket ("127.0.0.1", 6534); BufferedReader br = new BufferedReader (new FileReader ("c: \ data.txt "); PrintWriter Out = new PrintWriter (socket. getOutputStream (), true); String line = null; while (line = br. readLine ())! = Null) {out. println (line);} // out. println ("over"); // *. during development, the application timestamp is usually used to mark the end. The timestamp is first sent to the server. After the input is complete, try again // There is a method socket in the socket. shutdownOutput (); // tell the server that data has been written. // read the socket stream BufferedReader brin = new BufferedReader (new InputStreamReader (socket. getInputStream (); String string String = brin. readLine (); System. out. println (string); br. close (); socket. close ();}}

* Note that missing write is easy to cause. Wait for cleanup. After the client inputs are complete, the server is still waiting. I do not know that the client has been entered, blocked, and waiting.

The demo is divided into two main functions.

Exercise 3: upload images

Upload images to the client

Public static void main (String [] args) throws IOException {UpText_Client ();} public static void UpText_Client () throws IOException {// create a client Socket socket = new Socket ("127.0.0.1", 6534); // read the image file FileInputStream FD = new FileInputStream ("c: \ 1.jpg"); // obtain the socket output stream and send the obtained image data to the server OutputStream out = socket. getOutputStream (); byte [] buf = new byte [1024]; int len = 0; while (len = Fi. read (buf ))! =-1) {out. write (buf, 0, len);} // tells the server that the client data has been sent and the socket is read. shutdownOutput (); InputStream in = socket. getInputStream (); byte [] buf2 = new byte [1024]; int len2 = in. read (buf2); String result = new String (buf2, 0, len2); System. out. println (result); socket. close (); FCM. close ();}


Upload images to the server

Public static void main (String [] args) throws IOException {UpText_Server ();} public static void UpText_Server () throws IOException {// create server ServerSocket ss = new ServerSocket (6534 ); // obtain the client Socket = ss. accept (); // read data from the client InputStream in = socket. getInputStream (); String ip = socket. getInetAddress (). getHostAddress (); System. out. println ("IP:" + ip + ".... connect "); // store the read data to a File. File dir = new File (" c: \ CopyPic111111111 "); if (! (Dir. exists () {dir. mkdirs ();} File file = new File (dir, ip + ". jpg "); FileOutputStream fos = new FileOutputStream (file); byte [] buf = new byte [1024]; int len = 0; while (len = in. read (buf ))! =-1) {fos. write (buf, 0, len);} // gets the socket output stream and displays the upload result OutputStream out = socket. getOutputStream (); out. write ("Upload successful ". getBytes (); fos. close (); socket. close (); ss. close ();}

The server of the code above can only obtain one client for upload, but cannot upload multiple clients.

If the server obtains client 1 and is processing client 1, the client 2 must wait. If the waiting time is too long, the connection times out, the client object can be retrieved as a thread, and the client information can be processed as a thread without stopping switching, so that multiple clients can upload images to the server.


Improve the service end by combining threads

Client part unchanged

Server

Import java. io. IOException; import java.net. serverSocket; import java.net. socket; public class Up {private static ServerSocket ss; public static void main (String [] args) throws IOException {UpText_Server ();} public static void UpText_Server () throws IOException {ss = new ServerSocket (6534); while (true) {Socket socket = ss. accept (); // keeps receiving the new Thread (new UPtask (socket) of the client object )). start (); // create multiple threads to execute different client information }}}

Server thread

Public class UPtask implements Runnable {private Socket socket; public UPtask (Socket socket) {this. socket = socket;} public void run () {int count = 1; try {String ip = socket. getInetAddress (). getHostAddress (); System. out. println ("IP:" + ip + ".... connect "); InputStream in = socket. getInputStream (); File dir = new File ("c: \ CopyPic111111111"); if (! (Dir. exists () {dir. mkdirs ();} File file = new File (dir, ip + ". jpg "); // If a while (file. exists () {file = new File (dir, ip + "(" + (count ++) + "2.16.jpg");} FileOutputStream fos = new FileOutputStream (file ); byte [] buf = new byte [1024]; int len = 0; while (len = in. read (buf ))! =-1) {fos. write (buf, 0, len);} // gets the socket output stream and displays the upload result OutputStream out = socket. getOutputStream (); out. write ("Upload successful ". getBytes (); fos. close (); socket. close () ;}catch (Exception e) {// TODO: handle exceptionthrow new RuntimeException ("server Exception, please wait ");}}}





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.