Java Learning 62nd Lesson-TCP protocol Exercises

Source: Internet
Author: User

Learn about TCP's problems during the transfer process by practicing


Exercise 1: Create an English capital conversion server

The client enters the alphabetic data, sends it to the server, the server receives it and displays it to the console, and turns the data back to the client, knowing that the client input over, the conversion is over.

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 {//Text to server/* Convert server Side * 1. Create a ServerSocket server object * 2. Get the Socket Object * 3 . Source: Socket, read client sent over data needed to convert * 4. Sinks: Displayed in the console * 5. Turn data into uppercase returns the client *///create the service-side object ServerSocket SS = new ServerSocket (6534);// Gets the socket object socket socket = ss.accept ();//Gets the IP, which is explicitly who connected the string IP = socket.getinetaddress (). gethostaddress (); System.out.println ("IP:" +ip);//Get socket read stream and decorate BufferedReader br = new BufferedReader (New InputStreamReader (                      Socket.getinputstream ()));//get 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);p w.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/* Convert client: * 1. Create Socket Client Object * 2. Get keyboard Entry * 3. Send the input information to the socket output stream */socket socket = n EW Socket ("127.0.0.1", 6534); BufferedReader br = new BufferedReader (new InputStreamReader (system.in));//Source: 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 uppercase 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 uppercase information returned by the server string str = Br2.readline (); System.out.println ("Up:" +str);} Socket.close ();}}

Problems:

One, the above code has a problem, is the client input over after the end of the client, the server end?

End, the ReadLine () method is a blocking method, but after the client enters over, the client's socket close returns a-1, and the Read method in the service-side ReadLine () method reads-1, so the ReadLine () method reads to NULL, So it ends.


What happens if the automatic refresh of the PrintWriter pw = new PrintWriter (Socket.getoutputstream ()) on the client and the server is removed, and the auto-wrap of the Pw.print () is removed?

The client does not receive the converted data, the server does not display the data

Because the data written to the client, Pw.print () is written to the PrintWriter, and is not flushed into the socket input stream

PS: This is the TCP in the transmission process occurs at both ends of the situation is waiting, it is likely that the data is not sent out, the most likely is the blocking method.

Of course, can be in Pw.print (), Pw.flush (), but the problem is still, because ReadLine read the end of the tag is a newline, so in the client's pw.print (+ "\ r \ n"), so in order to solve the problem, the client and the server will be added to the refresh action, and newline characters.

In the case of the above problems, it is generally because of the blocking method caused by the service side, the client is waiting, so according to the above code example is written, better


Exercise 2: Uploading 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 line = 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);p w.println ("Upload succeeded"); 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");//*, the time of developmentGeneral is the application timestamp, do the end tag, first sent to the server a time stamp, the input is finished, and then sent once//socket there is a method socket.shutdownoutput ();//Tell the service end that the data has been finished// Read the socket stream BufferedReader brin = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); String string = Brin.readline (); System.out.println (string); Br.close (); Socket.close ();}}

* Note that the missing write easy to cause, waiting for cleanup, the client input is finished, the server is still waiting, do not know that the client has been entered, blocking, waiting

Demo, divided into two main functions of the demo

Exercise 3: Uploading pictures

Uploading images to the client

public static void Main (string[] args) throws Ioexception{uptext_client (); public static void Uptext_client () throws IOException {//CREATE client socket socket = new Socket ("127.0.0.1", 6534);// Read the picture file that the client wants to upload fileinputstream FIS = new FileInputStream ("c:\\1.jpg");//Get the socket output stream and send the resulting picture data to the server outputstream out = Socket.getoutputstream (); byte[] buf = new Byte[1024];int len = 0;while ((len = Fis.read (buf))!=-1) {out.write (buf, 0, Len); }//tells the server that the client has finished sending the data to the end of the Socket.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 (); Fis.close ();}


Uploading images to the service side

public static void Main (string[] args) throws IOException {Uptext_server ();} public static void Uptext_server () throws IOException {//Create server-side ServerSocket ss = new ServerSocket (6534);//Get Client Socket sock ET = ss.accept ();//Read the data sent by the client InputStream in = Socket.getinputstream (); String IP = socket.getinetaddress (). gethostaddress (); System.out.println ("IP:" +ip+ "... connect");//Store the read data into a file DIR = new file ("c:\\copypic111111111"); 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, showing the upload result outputstream out  = Socket.getoutputstream (); Out.write ("Upload succeeded". GetBytes ()); Fos.close (); Socket.close (); Ss.close ();}

The service side of the above code can only get one client upload, but not many.

Server to obtain the 1th client is processing 1th client, then 2nd client must wait, wait too long, will connect time-out, so the server-bound thread, get the client object as a thread, processing the client information as a thread, non-stop switching, you can implement multiple clients upload images to the server


Server-side bonding thread, improving

The client part is not changed

Service side

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 () ;//constantly receive client object new thread (new Uptask (socket)). Start ();//Create multiple threads to execute different client information}}}

Service 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"); Dir.exists ())) {Dir.mkdirs ();} File File = new file (dir,ip+ ". jpg");//if already exists while (file.exists ()) {file = new file (dir,ip+ "(" + (count++) + "). 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, showing the upload result outputstream out  = Socket.getoutputstream (); Out.write ("Upload succeeded". GetBytes ()); Fos.close (); Socket.close ();} catch (Exception e) {//Todo:handle Exceptionthrow new RuntimeException ("Server exception, please wait");}}}





Java Learning 62nd Lesson-TCP protocol Exercises

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.