1 public void await() {
2 // 创建ServerSocket对象
3 InetAddress add = null;
4 ServerSocket ss = null;
5 try {
6 add = InetAddress.getByName(LOCAL);
7 ss = new ServerSocket(port, blocklog, add);
8 } catch (IOException e) {
9 e.printStackTrace();
10 }
11 // 如果URI是/SHUTDOWN说明需要关闭服务器
12 Socket s = null;
13 InputStream in = null;
14 OutputStream out = null;
15 // 进入循环,知道响应完成
16 while (!shutdown) {
17 try {
18 //接收socket并创建流
19 s = ss.accept();//只会在8080端口接收到一个HTTP请求的时候才返回
20 in = s.getInputStream();
21 out = s.getOutputStream();
22 // 创建Request对象并parse,获取资源uri
23 Request request = new Request(in);
24 request.parse();
25 // 创建Response对象并执行操作
26 Response response = new Response(out);
27 // 传入Request对象,根据getUri()获取uri地址并进行加载
28 response.setReqest(request);
29 response.sendStaticResource();
30 // 关闭socket,同时输入流和输出流自动关闭
31 s.close();
32 // 检查返回的URI是否是服务器关闭命令
33 shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
34 } catch (Exception e) {
35 e.printStackTrace();
36 //出现异常就继续重新接收
37 continue;
38 }
39 }
40 }
在这里用的是Exception而不是IOException,这里使用Exception是为了保证捕获异常后可以继续维持JVM的运行.如果Exception换成IOException后,一旦出现IO异常,便会捕获停止运行.
下面是运行结果(Exception)
如果抛出的是IOException
明显看出后者导致JVM停止
转载于https://www.cnblogs.com/sunnysola/p/4927863.html