简体   繁体   中英

Java: coding for persistent connections

So I'm creating a web server. I think I've got everything pretty much good to go, but the one thing that is baffling me is persistent connections. I've got the logic set up so that it will detect if 'Close connection' was specified. If so it will close the connection and open a new one. Otherwise it will detect that connection should be kept alive. Where I'm getting lost is how to implement keeping the connection alive.

The server will read each line of the header and, after doing so (and after writing the requested information), it will funnel into one of these two statements depending on whether we want to persist the connection:

if (!keepAlive) {

System.out.println("close");
clientSocket.close();
in.close();
write.close();

}else{
System.out.println("keep alive");
}

This if-else statement comes within a continuous while loop. I think I've got the non-persist part set up correctly. Any advice on how to implement persistence?

All you have to do is loop reading requests, instead of just reading a single one. Set a read timeout so you don't get stuck there indefinitely. Break out of the loop if you read EOS instead of a request, or if Connection: close was specified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM