1. 如何启动?
main 方法是程序的入口, tomcat 也不例外, 查看 tomcat 源码, 发现 main 是在 Bootstrap 类中的;
2. 如何建立连接?
要通讯, 必须要建议 socket 连接, 我们需要使用哪种 socket, 是根据它使用的哪种协议进行判断的. tcp 协议 or udp 协议? http 协议本身属于 tcp 协议, 因此我们选择的 socket 是基本 tcp 协议的 socket. 在 tomcat 中, StandardServer 中 await() 方法具体实现了 socket 连接;
3. 使用哪种 io 模式?
BIO 方式适用于连接数目比较小且固定的架构, 这种方式对服务器资源要求比较高;
NIO 方式适用于连接数目多且连接比较短 (轻操作) 的架构, 比如聊天服务器;
AIO 方式使用于连接数目多且连接比较长 (重操作) 的架构, 比如相册服务器
tomcat 使用了 io,bio,nio,apr 三种 io 模式, 它们不同的应用各自发挥其优点. 这里通过 bio 简单实现一个 tomcat 服务.
代码示例:
- public class Server {
- public static void main(String[] args) throws IOException {
- new Server().start();
- }
- public void start() throws IOException {
- ServerSocket serverSocket = new ServerSocket(8888);
- Socket socket = null;
- System.out.println("启动 web 服务");
- while (true) {
- socket = serverSocket.accept();
- Thread thread = new Thread(new HttpServerThread(socket));
- thread.start();
- }
- }
- // 内部类
- private class HttpServerThread implements Runnable {
- Socket socket = null;
- HttpServerThread(Socket socket) {
- this.socket = socket;
- }
- @Override
- public void run() {
- InputStream is = null;
- OutputStream os = null;
- BufferedReader br = null;
- try {
- is = this.socket.getInputStream();
- os = this.socket.getOutputStream();
- // 页面的请求
- br = new BufferedReader(new InputStreamReader(is));
- String line = br.readLine();
- int i = 0;
- while (null != line && br.ready()) {
- line = br.readLine();
- System.out.println("第" + i + "行信息:" + line);
- i++;
- }
- // 页面的响应
- String reply = "HTTP/1.1\n"; // 必须添加的响应头
- reply += "Content-type:text/html\n\n"; // 必须添加的响应头
- reply += "服务器返回的消息";
- os.write(reply.getBytes());
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- os.close();
- is.close();
- socket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
在浏览器上输入: http://localhost:8888/
来源: http://www.bubuko.com/infodetail-2689466.html