JavaSE:在线考试系统(1)

1.  创建 ServerInitClose.java,实现服务器的初始化 & 关闭

位置:

    

代码:     

 1 package com.lagou.server;
 2 
 3 import java.io.IOException;
 4 import java.io.ObjectInputStream;
 5 import java.io.ObjectOutputStream;
 6 import java.net.ServerSocket;
 7 import java.net.Socket;
 8 
 9 // 编程实现:服务器的初始化 & 关闭
10 public class ServerInitClose {
11 
12     // 自定义成员变量, 来记录Socket和流对象
13     private ServerSocket ss;
14     private Socket s;
15     private ObjectInputStream ois;
16     private ObjectOutputStream oos;
17 
18     // 定义serverInit()方法,实现服务器的初始化
19     public void serverInit() throws IOException {
20 
21         // 1. 创建ServerSocket类型的对象,并提供端口号
22         ss = new ServerSocket(8888);
23 
24         // 2. 等待客户端的连接请求,调用accept方法
25         System.out.println("等待客户端的连接请求...");
26         s = ss.accept();
27         System.out.println("客户端连接成功!");
28 
29         // 3. 创建输入输出流,用于通信
30         ois = new ObjectInputStream(s.getInputStream());
31         oos = new ObjectOutputStream(s.getOutputStream());
32         System.out.println("服务器初始化成功!");
33     }
34 
35     // 定义serverClose()方法, 实现服务器的关闭
36     public void serverClose() throws IOException {
37 
38         // 4. 关闭Socket, 并释放有关的资源
39         oos.close();
40         ois.close();
41         s.close();
42         ss.close();
43         System.out.println("服务器成功关闭!");
44     }
45 
46 }

2.  创建 ServerTest.java, 用来 测试 服务器的初始化 & 关闭 功能

位置:

    

代码:

 1 package com.lagou.test;
 2 import com.lagou.server.ServerInitClose;
 3 import java.io.IOException;
 4 
 5 public class ServerTest {
 6     public static void main(String[] args) {
 7 
 8         ServerInitClose sic = null;
 9 
10         try {
11             // 1. 声明ServerInitClose类型的引用,指向该类型的对象
12             sic = new ServerInitClose();
13             // 2. 调用成员方法,实现服务器的初始化
14             sic.serverInit();
15         } catch (IOException e) {
16             e.printStackTrace();
17         } finally {
18             // 3. 调用成员方法,实现服务器的关闭
19             try {
20                 sic.serverClose();
21             } catch (IOException e) {
22                 e.printStackTrace();
23             }
24         }
25     }
26 }

运行测试类中的main方法:

 运行效果:

 
 

原文地址:https://www.cnblogs.com/JasperZhao/p/14971754.html