Java socket communication and possible problem resolution

Source: Internet
Author: User

Tag: While automatic port number resolves src construct break reason Boolean

In Java, two classes of network communication based on the TCP protocol: the client socket and the server-side ServerSocket.

Socket Communication Model:

Regardless of how complex the socket communication is, the basic structure of any socket communication process is the same. The basic steps are:

① creates sockets and ServerSocket instances on both the client and server side, and the server side waits for requests and blocks through the. Accept () method. After the request is received, the connection socket object is established.

② Open the input and output streams on the client and server side, respectively , via the getInputStream and Getoutputstream methods

③ using IO stream for Read and write operations

④ close all streaming resources and socket resources.

Among them, the programming work mainly focuses on the third step, the other part of the code is basically the same. All steps can throw an IO exception!

When I was writing a simple socket program, there was a problem with the socket communication: The data I wrote on the client was not output on the server side. When I disconnect from the client, all previously written data is immediately output on the server side. After repeated verification and solution, here are my conclusions and solutions. Hope to have the same problem of the small partners to finish reading can solve the problem.

The PrintWriter class is established through the socket at one end to write the data, and the BufferedReader class is established through the socket on the other end to read the data and output it. If the data is not displayed after it is written, there are two possible reasons:

The data that is written is stored in the buffer and is not written to the IO stream:

If you do not actively intervene, the data that is written is always stacked in the buffer until the buffer is full and the JVM automatically flushes the buffer. This is obviously not in line with our needs. In this case, the PrintWriter class provides the flush () method to force flushing the buffer and writes the buffer data to the IO stream. In addition, the constructor for the PrintWriter class has a parameter of "Boolean AutoFlush", which defaults to false, and if set to true, the Auto flush buffer function is turned on. Note, however, that the automatic refresh here has a trigger condition: The PrintWriter class must write the data in the println, printf, or Format method to trigger an automatic refresh. If a method called write () writes data, it does not trigger an automatic refresh! Summed up, is three points: AutoFlush parameter settings, write and println method selection, the use of the Flush method. By combining these three, the data can be guaranteed to be successfully written to the IO stream when the data is written at one end of the socket communication!

Second, read the data using the ReadLine () method, the method does not have a normal end:

Note that the ReadLine () method of the BufferedReader class is a blocking function! In other words, the method itself reads a row of data, but it does not recognize what is called a "line"! When the method is called to read a piece of data, it blocks without return its read data. This is why sometimes it is clear that the buffer has been correctly written to the data, or read the data through the input stream and display the reason.

For the ReadLine () method, it unblocked, ends correctly, and returns the Read value in the following cases:

The data read by ① contains a carriage return "\ r" or a newline character "\ n" or a carriage return line "\ r \ n";

The data read by ② is written by the Println method at the other end, since the println method has a newline character;

The buffer of the ③bufferedreader class is full, and the JVM automatically flushes the buffer to free the "accumulated" data (but since the default buffer size is 8,192 characters, it is obviously not triggered for small data volumes);

④ for the read data, the stream that writes the data is abnormal or shuts down directly, then ReadLine () will spit out all the data it eats. This explains why, in my program, the client socket connection is disconnected and the server side immediately outputs all client messages.

In conclusion, in the socket communication process, to ensure that one end of the output stream buffer is refreshed, to ensure that the other end of the ReadLine method can be stopped normally, you can solve the write data on the other end can not output problems.

Here are the code that I modified to run successfully, namely the server-side socket and the client socket.

over!

ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;ImportJava.net.ServerSocket;ImportJava.net.Socket;ImportJava.io.BufferedWriter;ImportJava.io.OutputStreamWriter; Public classshakingserver{ Public Static voidMain (string[] args)throwsIOException {//Create a server socket instance and set the listening port toServerSocket server=NewServerSocket (2000); //starts listening for client requests and blocksSocket socket=server.accept (); //after the request is received, the connection is established automatically. Data transfer via IO streamSYSTEM.OUT.PRINTLN ("Connection established successfully"); OutputStream OS=Socket.getoutputstream (); PrintWriter PW=NewPrintWriter (NewBufferedWriter (NewOutputStreamWriter (OS)),true); Pw.write ("Welcome to the world of shaking Jesus!" ");                Pw.flush (); //because I turned off the output stream, the ReadLine method at the other end ended normally.Socket.shutdownoutput (); InputStream is=Socket.getinputstream (); InputStreamReader ISR=NewInputStreamReader (IS); BufferedReader BR=NewBufferedReader (ISR);  while(true) {String str=Br.readline (); if(Str.equals ("Quit")) {                 Break; } System.out.println ("Client said:" +str);        } socket.shutdowninput (); //socket.shutdownoutput ();Socket.close ();    Server.close (); }}
ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter;ImportJava.io.PrintWriter;ImportJava.net.Socket; Public classshakingclient{ Public Static voidMain (string[] args)throwsioexception{//create a socket for the client, set the IP address and port number of the connected serverSocket socket=NewSocket ("169.254.132.203", 2000); //input Stream reads the information sent by the serverBufferedReader br=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); //turn on auto flush bufferPrintWriter pw=NewPrintWriter (NewBufferedWriter (NewOutputStreamWriter (Socket.getoutputstream ())),true); //reading data from the keyboardBufferedReader ii=NewBufferedReader (NewInputStreamReader (system.in));               System.out.println (Br.readline ()); //because automatic refresh is turned on and the Println method is called, you can not call the Flush methodPW.PRINTLN ("Request to enter the world of Jesus in his head"); //Pw.flush ();         while(true) {String str=Ii.readline (); //A carriage return is used to ensure that the ReadLine method at the other end ends normally .Pw.write (str+ "\ r");                Pw.flush (); //quit chat Room If you enter quit            if(Str.equals ("Quit")) {                 Break;        }} socket.shutdowninput ();        Socket.shutdownoutput ();    Socket.close (); }}                

Java socket communication and possible problem resolution

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.