Java Socket Communications Introduction and solve problems you might encounter _java - JAVA

Source: Hi learning network sensitive and eager Forum www.piaodoo.com welcome to learn from each other

Foreword

This paper to introduce relevant content on the Java Socket Communications, learning to share for your reference, the following did not talk much to say, to take a look at the detailed introduction.

Java in network communication based on TCP protocol two categories: Socket and ServerSocket server client.

Socket communication model shown in FIG:

Hi learning network

No matter how complex functions Socket Communications, the basic structure of any socket communication process is the same.

The basic steps:

      Socket and ServerSocket ① create separate instances of the client and server; server through .accept () method waits for requests and blocks. After receipt of the request, to establish a connection Socket object.

      ② open and the input and output streams through getInputStream Methods getOutputStream the client and server

      ③ IO stream read and write operations using

      ④ close all sockets resources and resource flows.

Wherein programming mainly in the third step, the other part of the code is substantially the same. All steps are likely to throw an IO exception!

When I write a simple socket program, Socket used for communication there is a problem: I write data on the client side, it can not be output on the server side. When I disconnect from the client, all data is written immediately before the output came out on the server side. After repeated verification and solution, the following are my conclusions and solutions. We want to have the same problem of a small partner reading can solve the problem.

Socket established by the end of the PrintWriter data is written, the other end through the Socket BufferedReader established class to read and output data.

If the data is not written to the display, there are two possible reasons:

A write data is stored in the buffer, the stream is not written IO:

If you do not take the initiative to interference, the data will always be written in a heap buffer until the buffer is full caused JVM auto-refresh buffer. Obviously this does not meet our needs. In this case, the PrintWriter class provides flush () method to force a refresh buffer, the buffer write data stream IO. In addition, the constructor PrintWriter class has a parameter "boolean autoflush", this parameter defaults to false, if set to true, it will turn on auto-refresh buffer function. Note, however, here are automatically refresh trigger conditions, that is: the method of writing data must PrintWriter class is println, printf, or format methods will trigger automatic refresh. If the call is a write () method to write this type of data, it will not trigger an automatic refresh! To sum up, it is three points: autoflush parameter settings, using the selected write and println methods, flush method. Combining these three, when data is written can guarantee a certain end Socket Communications, will be able to successfully written the data to the IO stream!

Second, the read data using the readLine () method, which is not normally ended:

Please note, readLine BufferedReader class () method is a blocking function! That is, after the method itself is to read a line of data, but they can not identify what it called a "line"! When you invoke this method has finished reading a piece of data, it will be blocked and will not return it to read data. That's why sometimes clearly has set a correct write data buffer, or by reading the input data stream and displayed reasons.

For readLine () method, which unblocked the right end and returns the value of reading, only the following situations:

      ① read data contains carriage return "\ r" or newline "\ n" or carriage return "\ r \ n";

      ② the read data is written, at the other end by the method as println println method comes newline;

      ③BufferedReader class buffer is full, the JVM will automatically refresh buffer to release the "accumulation" of data (but in view of the default buffer size is 8192 characters to communicate small amounts of data, can not apparently triggered);

      ④ For data read, writes the stream data directly off or abnormal, then all the readLine () it will eat data spit. It just explains why, in my program, disconnect the client Socket connection, the server immediately cause of all client output messages.

In summary, the Socket communication, one end of the output stream to ensure that the buffer is refreshed, the other end of the guaranteed readLine method can stop normally, data is written to solve the problem at the other end can not be output.

Here is the code I can run successfully modified, namely the client and server-side Socket Socket.

over!

java.io.BufferedReader Import; 
Import java.io.IOException; 
Import a java.io.InputStream; 
Import the java.io.InputStreamReader; 
Import a java.io.OutputStream; 
Import java.io.PrintWriter; 
Import the java.net.ServerSocket; 
Import the java.net.Socket; 
Import java.io.BufferedWriter; 
Import java.io.OutputStreamWriter; 
public class ShakingServer { 
 public static void main (String [] args) throws IOException { 

 // create a server socket instance, to set the listening port 2000 
 ServerSocket Server = new new ServerSocket (2000); 
 // start listening for client requests, and blocks 
 socket socket = server.accept (); 
 // after receipt of the request, automatically establish a connection. Data transmission through the IO stream 
 System.out.println ( "connection is established");
 
 the OutputStream Socket.getOutputStream OS = ();
 PrintWriter pw = new new PrintWriter (new new BufferedWriter (new new OutputStreamWriter (os)), to true); 
 pw.write ( "Welcome to the world of Jesus shook his head!"); 
 Pw.flush (); 
  // because I closed the output stream, so another method readLine normally end before the end of 
 socket.shutdownOutput (); 

 the InputStream Socket.getInputStream iS = (); 
 the InputStreamReader the InputStreamReader new new ISR = (iS); 
 the BufferedReader br = new new the BufferedReader (ISR); 
 the while (to true) { 
  String STR = br.readLine (); 
  IF (str.equals ( "quit")) { 
  BREAK; 
  } 
  System.out.println ( "Said Client:" + STR); 
 } 
 socket.shutdownInput (); 
 //socket.shutdownOutput () ; 
 the Socket.close (); 
 server.close (); 
 } 
}
java.io.BufferedReader Import; 
Import java.io.BufferedWriter; 
Import java.io.IOException; 
Import the java.io.InputStreamReader; 
Import java.io.OutputStreamWriter; 
Import java.io.PrintWriter; 
Import the java.net.Socket; 

public ShakingClient {class 
 public static void main (String [] args) throws IOException { 

 // create a client socket, the connection settings server IP address and port number 
 socket socket = new socket ( "169.254.132.203 ", 2000); 
 // read the input stream information server transmits 
 the BufferedReader the BufferedReader br = new new (new new the InputStreamReader (Socket.getInputStream ())); 
  // open the automatic refresh buffer 
 PrintWriter pw = new PrintWriter (new BufferedWriter (new OutputStreamWriter (socket.getOutputStream ( ))), true);   
  // read the data from the keyboard
 II = the BufferedReader new new the BufferedReader (the InputStreamReader new new (the System.in)); 
 System.out.println (br.readLine ()); 
  // open because of the auto-refresh, and the call is println method, it may not call flush 
 pw .println ( "request to enter his head Jesus world"); 
 //pw.flush (); 
 the while (to true) { 
  String = ii.readLine STR (); 
  // carriage used method to ensure that the other end of the normal readLine end 
  pw.write (STR + "\ R & lt"); 
  pw.flush (); 
  // if the input quit the exit IM 
  IF (str.equals ( "quit")) { 
  BREAK; 
  } 
 } 
 socket.shutdownInput (); 
 Socket .shutdownOutput (); 
 the Socket.close (); 
 } 
}

to sum up

That's all for this article, I hope the contents of this paper has some reference value of learning for all of us to learn or work, if in doubt you can leave a message exchange, thank you for the support sensitive and eager Forum / Hi learning network.

The original address is: http: //www.piaodoo.com/thread-13254-1-1.html stockings control www.txdah.com 131 outside www.buzc.org enjoyable learning can help to learn better!

Guess you like

Origin www.cnblogs.com/txdah/p/12093760.html