//httpServer.java import java.net.*; import java.io.*; import java.util.*; import java.lang.*; public class httpServer{ public static void main(String args[]) { int port; ServerSocket server_socket; //读取服务器端口号 try { port = Integer.parseInt(args[0]); } catch (Exception e) { port = 8080; } try { //监听服务器端口,等待连接请求 server_socket = new ServerSocket(port); System.out.println("httpServer running on port " + server_socket.getLocalPort()); //显示启动信息 while(true) { Socket socket = server_socket.aclearcase/" target="_blank" >ccept(); System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort()); //创建分线程 try { httpRequestHandler request = new httpRequestHandler(socket); Thread thread = new Thread(request); //启动线程 thread.start(); } catch(Exception e) { System.out.println(e); } } } catch (IOException e) { System.out.println(e); } } } class httpRequestHandler implements Runnable { final static String CRLF = "\r\n"; Socket socket; InputStream input; OutputStream output; BufferedReader br; // 构造方法 public httpRequestHandler(Socket socket) throws Exception { this.socket = socket; this.input = socket.getInputStream(); this.output = socket.getOutputStream(); this.br = new BufferedReader(new InputStreamReader(socket.getInputStream())); } // 实现Runnable 接口的run()方法 public void run() { try { processRequest(); } catch(Exception e) { System.out.println(e); } } private void processRequest() throws Exception { while(true) { //读取并显示Web 浏览器提交的请求信息 String headerLine = br.readLine(); System.out.println("The client request is "+headerLine); if(headerLine.equals(CRLF) || headerLine.equals("")) break; StringTokenizer s = new StringTokenizer(headerLine); String temp = s.nextToken(); if(temp.equals("GET")) { String fileName = s.nextToken(); fileName = "." + fileName ; // 打开所请求的文件 FileInputStream fis = null ; boolean fileExists = true ; try { fis = new FileInputStream( fileName ) ; } catch ( FileNotFoundException e ) { fileExists = false ; } // 完成回应消息 String serverLine = "Server: a simple java httpServer"; String statusLine = null; String contentTypeLine = null; String entityBody = null; String contentLengthLine = "error"; if ( fileExists ) { statusLine = "HTTP/1.0 200 OK" + CRLF ; contentTypeLine = "Content-type: " + contentType( fileName ) + CRLF ; contentLengthLine = "Content-Length: " + (new Integer(fis.available())).toString() + CRLF; } else { statusLine = "HTTP/1.0 404 Not Found" + CRLF ; contentTypeLine = "text/html" ; entityBody = "<HTML>" + "<HEAD><TITLE>404 Not Found</TITLE></HEAD>" + "<BODY>404 Not Found" +"<br>usage:http://yourHostName:port/" +"fileName.html</BODY></HTML>" ; } // 发送到服务器信息 output.write(statusLine.getBytes()); output.write(serverLine.getBytes()); output.write(contentTypeLine.getBytes()); output.write(contentLengthLine.getBytes()); output.write(CRLF.getBytes()); // 发送信息内容 if (fileExists) { sendBytes(fis, output) ; fis.close(); } else { output.write(entityBody.getBytes()); } } } //关闭套接字和流 try { output.close(); br.close(); socket.close(); } catch(Exception e) {} } private static void sendBytes(FileInputStream fis, OutputStream os) throws Exception { // 创建一个 1K buffer byte[] buffer = new byte[1024] ; int bytes = 0 ; // 将文件输出到套接字输出流中 while ((bytes = fis.read(buffer)) != -1 ) { os.write(buffer, 0, bytes); } } private static String contentType(String fileName) { if (fileName.endsWith(".htm") || fileName.endsWith(".html")) { return "text/html"; } return "fileName"; } } |
编程技巧说明 ◆ 主线程设计 主线程的设计就是在主线程httpServer 类中实现了服务器端口的侦听,服务器接受一个客户端请求之后创建一个线程实例处理请求,代码如下:
◆ 连接处理分线程设计 在分线程httpRequestHandler 类中实现了HTTP 协议的处理,这个类实现了Runnable 接口,代码如下:
◆ 构建processRequest()方法来处理信息的接收和发送 作为实现Runnable 接口的主要内容,在run()方法中调用processRequest()方法来处理客户请求内容的接收和服务器返回信息的发送,代码如下:
在processRequest()方法中得到客户端请求后,利用一个StringTokenizer 类完成了字符串的拆分,这个类可以实现根据字符串中指定的分隔符(缺省为空格)将字符串拆分成为字串的功能。利用nextToken()方法依次得到这些字串;sendBytes()方法完成信息内容的发送,contentType()方法用于判断文件的类型。 显示Web页面 显示 Web 页面的index.html 文件代码如下:
运行实例 为了测试上述程序的正确性,将编译后的httpServer.class、httpRequestHandler.class和上面的index.html文件置于网络的某台主机的同一目录中。 首先运行服务器程序 java httpServer 8080,服务器程序运行后显示端口信息“httpServer runing on port 8080”, 然后在浏览器的地址栏中输入http://localhost:8080/index.html,就可以正确显示网页,同时在显示“httpServer runing on port 8080 ”窗口中服务器会出现一些信息。 |