Background:
Today, I found a problem when simulating socket request
//Test code public static void http(String path) throws Exception { URL url = new URL(path); final String host = url.getHost(); //If the port is specified, get the port, otherwise - 1 int port = url.getPort(); int defaultPort = url.getDefaultPort(); final String file = url.getFile(); Socket socket = new Socket(host, port == -1 ? defaultPort : port); InputStream is = socket.getInputStream(); final BufferedReader br = new BufferedReader(new InputStreamReader(is)); final OutputStream os = socket.getOutputStream(); //Open a thread to read data new Thread(){ @Override public void run() { String line; try { while ((line = br.readLine()) != null){ Log.e("TAG",line); } } catch (IOException e) { e.printStackTrace(); } } }.start(); //Open a thread to send data new Thread(){ @Override public void run() { SystemClock.sleep(10000); try { //Request line os.write(("GET "+file+" HTTP/1.1\r\n").getBytes()); os.write(("Host: "+host+"\r\n").getBytes()); os.write(("\r\n").getBytes()); os.flush(); }catch (Exception e){ } } }.start(); /* //Request line os.write(("GET "+file+" HTTP/1.1\r\n").getBytes()); os.write(("Host: "+host+"\r\n").getBytes()); os.write(("\r\n").getBytes()); os.flush();*/ }
You can see through the code:
I used two tests:
First time: open a thread to read the data. The sending data is not sent in the sub thread, but under the data reading method. As a general rule, such code will first execute the method of reading data. Results through breakpoint debugging, it is found that the method of sending data is executed first, and then the method of reading data is executed. It may be said here that it takes a little time to start a thread. OK, so I have a second test.
The second time (such as the above code): I also execute the code of sending data in the z thread, and execute the code of sending data after sleeping for 10 seconds in the thread. The result is the same as above: the code of sending data executed first, and then the method of reading data executed.
In fact, there is a misunderstanding about the readLine () method. The error is that readLine() returns null when no data is read. In fact, readLine () is a blocking function. When there is no data to read, it will cause IO blocking, and this method will always block here. Therefore, readLine() will read the data only after the method sending the data is executed, and then the following will execute normally.