简单的java web服务器实例

  编写使用java语言实现的Web服务器,主要通过使用java socket 编程来实现,使用java socket编程不仅可以编写web服务器,还可以编写其他网络应用。

WebServer.java

package webbook.chapter2;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class WebServer {
 /** 默认使用的服务器Socket端口号 */
 public static final int HTTP_PORT = 8080;
 private ServerSocket serverSocket;

 public void startServer(int port) {
  try {
   serverSocket = new ServerSocket(port);
   System.out.println("Web Server startup on  " + port);
   while (true) {
    Socket socket = serverSocket.accept();
    // 通过线程的方式来处理客户的请求
    new Processor(socket).start();
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

 /**
  * WebServer类的启动方法,可以通过命令行参数指定当前Web服务器所使用的端口号。
  */
 public static void main(String[] argv) throws Exception {
  WebServer server = new WebServer();
  if (argv.length == 1) {
   server.startServer(Integer.parseInt(argv[0]));
  } else {
   server.startServer(WebServer.HTTP_PORT);
  }
 }
}

Processor.java

package webbook.chapter2;

import java.io.*;
import java.net.Socket;

/**
 * 处理一个HTTP用户请求的线程类。
 */
public class Processor extends Thread {
 private PrintStream out;
 private InputStream input;
 /** 默认的服务器存放访问内容的目录D:\eclipse3.4\workspace03 */
 public static final String WEB_ROOT = "d:\\eclipse3.4\\workspace03\\webserver2\\htdocs";

 public Processor(Socket socket) {
  try {
   input = socket.getInputStream();
   out = new PrintStream(socket.getOutputStream());
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

 public void run() {
  try {
   String fileName = parse(input);
   readFile(fileName);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

 /**
  * 解析客户机发过的所有HTTP请求,如果是符合HTTP协议内容的, 就分析出客户机所要访问文件的名字,并且返回文件名。
  */
 public String parse(InputStream input) throws IOException {
  BufferedReader in = new BufferedReader(new InputStreamReader(input));
  String inputContent = in.readLine();
  if (inputContent == null || inputContent.length() == 0) {
   sendError(400, "Client invoke error");
   return null;
  }
  // 分析客户请求的HTTP信息,分析出到底想访问哪个文件,
  // 发过来的HTTP请求应该是三部分。

  String request[] = inputContent.split(" ");
  if (request.length != 3) {
   sendError(400, "Client invoke error");
   return null;
  }
  // 第一部分是请求的方法
  String method = request[0];
  // 第二部分是请求的文件名
  String fileName = request[1];
  // 第三部分是HTTP版本号
  String httpVersion = request[2];
  System.out.println("Method: " + method + ", file name: " + fileName + ", HTTP version: " + httpVersion);
  return fileName;
 }

 /**
  * 处理调用一个文件的请求
  */
 public void readFile(String fileName) throws IOException {
  File file = new File(Processor.WEB_ROOT + fileName);
  if (!file.exists()) {
   sendError(404, "File Not Found");
   return;
  }
  // 把文件的内容读取到in对象中。
  InputStream in = new FileInputStream(file);
  byte content[] = new byte[(int) file.length()];
  in.read(content);
  out.println("HTTP/1.0 200 sendFile");
  out.println("Content-length: " + content.length);
  out.println();
  out.write(content);
  out.flush();
  out.close();
  in.close();
 }

 /**
  * 发送错误的信息
  */
 public void sendError(int errNum, String errMsg) {
  out.println("HTTP/1.0 " + errNum + " " + errMsg);
  out.println("Content-type:text/html");
  out.println();
  out.println("<html>");
  out.println("<meta content='text/html; charset=gb2312' http-equiv='Content-Type'/>");
  out.println("<head><title>Error " + errNum + "--" + errMsg + "</title></head>");
  out.println("<h1>" + errNum + " " + errMsg + "</h1>");
  out.println("</html>");
  out.println();
  out.flush();
  out.close();
  System.out.println(errNum+",,,,"+errMsg);
 }
}

在“e:\workspace\webserver” 目录下建立一个htdocs目录,存放需要被访问的html文件等资源。然后运行WebServer类,启动这个Web服务器程序,就可以通过浏览器访问这个服务器了。http://localhost:8080/welcome.html

其实看书还是很重要的,许多细节都在书中有解释。以上例子就是在翻看两年前发的书上看到的。初学时不一定能看懂,但等过了许久回过头来一看原来如此。。。

转载于:https://my.oschina.net/zhk/blog/72245

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值