There was a problem writing a server with a socket and then the main problem was drawn out, the code is as follows, because the code is simple and there is no comment.
public class Main {private static ServerSocket serversocket;
Private final static Executorservice exec = Executors.newfixedthreadpool (30);
public static void Main (string[] args) {try {serversocket = new ServerSocket (8888);
while (true) {Socket socket = serversocket.accept ();
Exec.execute (new serverrunnable (socket));
} catch (IOException e) {e.printstacktrace ();
Class Serverrunnable implements Runnable {private socket socket;
Private InputStream is;
Private OutputStream out;
Private String reqstr;
Private String rescontent;
Public serverrunnable (socket socket) {this.socket = socket;
@Override public void Run () {handlesocket (socket);
private void Handlesocket (socket socket) {try {byte[] buffer = new byte[1024];
is = Socket.getinputstream (); SystEm.out.println (IS);
out = Socket.getoutputstream ();
int len = 0;
StringBuilder sb = new StringBuilder ();
while (len = is.read (buffer))!=-1) {String str = new String (buffer, 0, Len);
Sb.append (str);
} reqstr = Sb.tostring ();
System.out.println (REQSTR);
Rescontent = "welcome!";
StringBuilder Resbuilder = new StringBuilder ();
Resbuilder.append ("http/1.1 OK"). Append ("\ r \ n").
Append ("Date:"). Append (new Date ()). Append ("\ r \ n").
Append ("Content-type:"). Append ("Text/plain;charset=utf-8"). Append ("\ r \ n").
Append ("Content-length:"). Append (Rescontent.getbytes (). Length). Append ("\ r \ n").
Append ("\ r \ n");
Resbuilder.append (rescontent);
Out.write (Resbuilder.tostring (). GetBytes ());
Socket.close ();
catch (IOException e) {e.printstacktrace (); }
}
}
The code is very simple, is written a socket server, through the browser to access localhost:8888 will return welcome!
But in the actual work, the dead and dead can not achieve the effect.
I thought it might be out of the data has not been written in, and then breakpoint debugging, but it is because of breakpoint debugging caused a long time did not find out the error.
1. At the time of testing there is such a phenomenon has not caught my attention: server-side print browser data from the Click to stop loading page/refresh will not print. (After knowing the truth, it's because the other end of the disconnect will jump out of the block and continue)
And I was in the test because the browser has not received server-side data and is constantly waiting for the state, I will refresh or visit again, and precisely because of such a stupid operation, the server side of the data printing, breakpoint debugging also went in, so I did not suspect for a long time because it did not come to this step. The suspicion is my computer where or the browser is not set up good.
2. Shielding the handlesocket inside the receiving client input code, just add to the data sent to the client, found that you can receive data, clear the data is not wrong, and finally found the above problem in the while loop interrupt point, finally found the program blocked there.
At first feel very strange, large file copying is not all done, how can also make mistakes, search the Internet, the socket in close, will send to the other end of the EOF, so that will read to the end of the flow of information and return-1.
Before writing a Java chat function in fact encountered such a problem, to quit chatting to send a specific character, and then in the break out of the loop, and then close the socket, so that the other end of the socket due to the end of the close off also jump out of the loop. Only now because of only write service end didn't think.
Because there is no way to know if the remote socket has anything to send. So read has never returned.
Read's document description is roughly: If no bytes are available because the end of the stream has been reached, then the value-1 is returned. This method blocks until the input data is available, the end of the stream is detected, or an exception is thrown.
Socket and file is not the same, read from the file, read to the end of the stream to reach the end, so will return-1 or null, loop end, but the socket is connected to the two host bridge, one end can not know the other end of the data to be transmitted.
If the socket is not closed, a blocking function such as read will wait for it to send data, which is called blocking.
Of course here we can adjust buffer buffers a bit larger, so that without the while loop, read only once, but other scenarios such as the data sent to a large one can not read, then only the while loop to deal with. The solution scenario under this scenario is shown below.
Four ways to solve:
1. Call the Socke Shutdownoutput method to turn off the output stream, which is documented by placing the output stream of this socket at the end of the stream so that the read operation on the other end of the input stream returns-1. Cannot call Socket.getinputstream (). Close (). This will cause the socket to be closed.
2. The end of the contract sign, when read to the end of the sign exit no longer read.
3. Set timeout, will throw the sockettimeoutexception exception when the set timeout time arrives and no longer block.
4. The length of the agreed good data in the head. The Read method is no longer invoked when the length of the reading is equal to this length.
In short, TCP can often cause code problems because of read/readline and stream processing functions such as blocking functions such as flush buffering. You must be careful.
The way one is generally used in both communication is controlled by the developer. Mode two has certain limitation, and both sides also must communicate good mark to end the Zhi. Mode three always feels bad, timeout should be used in other more meaningful places, such as the time limit when the network is bad. Mode four should be the best way, and most of the cases are done that way.
Obviously we can't use the way one here.
So I immediately came up with a question: What is the end sign of the HTTP protocol?
Seems to have found a few places to discuss the issue, see:
1. Topic: Learn the Java basics that spring must learn (9)--http message (series full) The end sign mentioned inside I tested it and it's not right.
2.http End of package flag
I have not studied the specifics of the HTTP protocol, only know that it is the socket and some of the format of the protocol, the other is not clear, but the current view should not let the server know the end of the data flag.
And then another question came to my mind: how does the Tomcat source parse the HTTP protocol header information?
I originally guessed that it would be through the fourth way because it contains the Content-length field, it's easy to get the total size. Roughly look at the source code, seemingly not yet, its use is NIO socket implementation,
Parsing HTTP headers is a byte parsing, but the code is too long, just read a general, more understanding can communicate with me to learn, appreciate.