Java socket 实现tomcat服务器

来源:互联网 发布:兰溪行知学院最新消息 编辑:程序博客网 时间:2024/04/28 03:22

一个基于java的web服务器使用这两个重要的类:java.net.Socket和java.net.ServerSocket,并通过HTTP消息进行通信。在实现Web服务器之前有必要简要说明一下超文本传输协议(HTTP)。

超文本传输协议(HTTP)

http是一种无状态的请求和相应协议,请大家暂时记住无状态这一概念,在后续介绍session时将会向大家阐述有状态和无状态的区别。在HTTP中,始终由客户端发送HTTP请求。web服务器从不主动联系客户端或对客户端做回调连接,服务器端只根据客户端发来的请求做出响应。下面将介绍HTTP请求HTTP响应Socket类

HTTP请求

一个HTTP请求包括三个组成部分:

1.方法—统一资源标示符(URI)—协议/版本

2.请求的头部

3.主体内容

示例如下:

[plain] view plaincopy
  1. POST /examples/default.jsp HTTP/1.1  
  2. Accept: text/plain; text/html  
  3. Accept-Language: en-gb  
  4. Connection: Keep-Alive  
  5. Host: localhost  
  6. User-Agent: Mozilla/4.0  
  7. Content-Length: 33  
  8. Content-Type: application/x-www-form-urlencoded  
  9. Accept-Encoding: gzip, deflate  
  10.   
  11. lastName=Franks&firstName=Michael  

HTTP响应

类似于HTTP请求,一个HTTP响应也包括三个组成部分:

1.方法-统一资源标示符(URI)-协议/版本

2.响应的头部

3.主体内容

下面是一个HTTP响应的例子:

[plain] view plaincopy
  1. HTTP/1.1 200 OK  
  2. Server: IBM/4.0  
  3. Date: Sat, 6 Nov 2013 13:13:00 GMT  
  4. Content-Type: text/html  
  5. Last-Modified: Sat, 5 Jan 2013 13:13:12 GMT  
  6. Content-Length: 112  


Socket类

套接字是网络连接的一个端点。套接字使得一个应用可以从网络中读取和写入数据。放在两个不同的计算机上的两个应用可以通过连接发送和接受字节流。为了从你的应用发送一条信息到另一个应用,你需要指导另一个应用的IP地址和套接字端口。

ServerSocket类

Socket类代表一个客户端套接字,即任何时候你想连接到一个远程服务器应用的时候你构造的套接字。如果是一个服务器程序依靠Socket类是行不通的。你的服务器必须随时待命,因为客户端何时想你发送请求是不知道的。

[plain] view plaincopy
  1.   

ServerSocket和Socket不同,服务器套接字的角色是等待来自客户端的连接请求。一旦服务器套接字获得一个连接请求,它创建一个Socket实例来与客户端进行通信。

下面我们来看看这三个类:

HttpServer类

[java] view plaincopy
  1. <strong>package com.vipshop.test;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.net.InetAddress;  
  8. import java.net.ServerSocket;  
  9. import java.net.Socket;  
  10. import java.net.UnknownHostException;  
  11.   
  12. import com.vipshop.tomcat.pyrmont.Request;  
  13. import com.vipshop.tomcat.pyrmont.Response;  
  14.   
  15. public class HttpServer {  
  16.   
  17.     public static final String WEB_ROOT = System.getProperty("user.dir")  
  18.             + File.separator + "webroot";  
  19.   
  20.     private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";  
  21.   
  22.     private boolean shutdown = false;  
  23.   
  24.     public static void main(String[] args) {  
  25.   
  26.         HttpServer server = new HttpServer();  
  27.         server.await();  
  28.   
  29.     }  
  30.   
  31.     public void await() {  
  32.   
  33.         ServerSocket serverSocket = null;  
  34.   
  35.         int port = 8080;  
  36.   
  37.         try {  
  38.             serverSocket = new ServerSocket(port, 1, InetAddress  
  39.                     .getByName("127.0.0.1"));  
  40.         } catch (UnknownHostException e) {  
  41.   
  42.             e.printStackTrace();  
  43.   
  44.         } catch (IOException e) {  
  45.   
  46.             e.printStackTrace();  
  47.             System.exit(1);  
  48.   
  49.         }  
  50.   
  51.         // Loop waiting for a request  
  52.         while (!shutdown) {  
  53.   
  54.             Socket socket = null;  
  55.             InputStream input = null;  
  56.             OutputStream output = null;  
  57.   
  58.             try {  
  59.                 socket = serverSocket.accept();  
  60.                 input = socket.getInputStream();  
  61.                 output = socket.getOutputStream();  
  62.   
  63.                 // create Request object and parse  
  64.                 Request request = new Request(input);  
  65.                 request.parse();  
  66.   
  67.                 // create Response object  
  68.                 Response response = new Response(output);  
  69.                 response.setRequest(request);  
  70.                 response.sendStaticResource();  
  71.   
  72.                 // Close the socket;  
  73.                 socket.close();  
  74.   
  75.                 // check if the revious URI is a shutdown command  
  76.                 shutdown = request.getUri().equals(SHUTDOWN_COMMAND);  
  77.             } catch (IOException e) {  
  78.   
  79.                 e.printStackTrace();  
  80.                 continue;  
  81.                   
  82.             }  
  83.   
  84.         }  
  85.   
  86.     }  
  87.   
  88. }  
  89. </strong>  
[java] view plaincopy
  1.    

 

Request类

[java] view plaincopy
  1. package com.vipshop.test;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5.   
  6. public class Request {  
  7.   
  8.     private InputStream input;  
  9.       
  10.     private String uri;  
  11.       
  12.     public Request(InputStream input) {  
  13.           
  14.         this.input = input;  
  15.           
  16.     }  
  17.       
  18.     public void parse() {  
  19.           
  20.         // Read a set of characters from the socket  
  21.         StringBuffer request = new StringBuffer(2018);  
  22.           
  23.         int i;        
  24.         byte[] buffer = new byte[2048];  
  25.           
  26.         try {  
  27.               
  28.             i = input.read(buffer);  
  29.               
  30.         } catch (IOException e) {  
  31.               
  32.             e.printStackTrace();  
  33.             i = -1;  
  34.         }  
  35.           
  36.         for (int j = 0; j < i; j ++) {  
  37.               
  38.             request.append((char)buffer[j]);  
  39.               
  40.         }  
  41.           
  42.         System.out.println();  
  43.         System.out.println("request.toString():");  
  44.         System.out.print(request.toString());  
  45.         System.out.println();  
  46.           
  47.         uri = parseUri(request.toString());  
  48.     }  
  49.       
  50.     private String parseUri(String requestString) {  
  51.           
  52.         int index1, index2;  
  53.           
  54.         index1 = requestString.indexOf(' ');  
  55.           
  56.         if (index1 != -1) {  
  57.               
  58.             index2 = requestString.indexOf(' ', index1 + 1);  
  59.               
  60.             return requestString.substring(index1 + 1, index2);  
  61.         }  
  62.           
  63.         return null;  
  64.           
  65.     }  
  66.       
  67.     public String getUri() {  
  68.           
  69.         return uri;  
  70.     }  
  71.       
  72. }  


Response类

[java] view plaincopy
  1. package com.vipshop.test;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.IOException;  
  6. import java.io.OutputStream;  
  7.   
  8. public class Response {  
  9.   
  10.     private static final int BUFFER_SIZE = 1024;  
  11.       
  12.     private Request request;  
  13.     private OutputStream output;  
  14.       
  15.     public Response(OutputStream output) {  
  16.           
  17.         this.output = output;  
  18.           
  19.     }  
  20.       
  21.     public void setRequest(Request request) {  
  22.           
  23.         this.request = request;  
  24.           
  25.     }  
  26.       
  27.     public void sendStaticResource() throws IOException {  
  28.           
  29.         byte[] bytes = new byte[BUFFER_SIZE];  
  30.         FileInputStream fis = null;  
  31.           
  32.         File file = new File(HttpServer.WEB_ROOT, request.getUri());  
  33.           
  34.         if (file.exists()) {  
  35.               
  36.             fis = new FileInputStream(file);  
  37.             int ch = fis.read(bytes, 0, BUFFER_SIZE);  
  38.               
  39.             while (ch != -1) {  
  40.                   
  41.                 output.write(bytes, 0, ch);  
  42.                 ch = fis.read(bytes, 0, BUFFER_SIZE);  
  43.                   
  44.             }  
  45.               
  46.         } else {  
  47.               
  48.             // file not found  
  49.             String errorMessage = "HTTP/1.1 404 File NOT Fount\r\n" +   
  50.             "Content-Type: text/html\r\n" +   
  51.             "Content-Length: 23\r\n" +  
  52.             "\r\n" +   
  53.             "<h1>File Not Found</h1>";  
  54.             output.write(errorMessage.getBytes());  
  55.         }  
  56.           
  57.         if (fis != null) {  
  58.               
  59.             fis.close();  
  60.               
  61.         }  
  62.           
  63.     }  
  64.       
  65. }  

 

原创粉丝点击