欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

简单实现Java web服务器

程序员文章站 2024-03-12 15:38:02
一个简单的java web服务器实现,比较简单,基于java.net.socket和java.net.serversocket实现; 一、程序执行步骤  1....

一个简单的java web服务器实现,比较简单,基于java.net.socket和java.net.serversocket实现;
一、程序执行步骤
 1.创建一个serversocket对象;
 2.调用serversocket对象的accept方法,等待连接,连接成功会返回一个socket对象,否则一直阻塞等待;
 3.从socket对象中获取inputstream和outputstream字节流,这两个流分别对应request请求和response响应;
 4.处理请求:读取inputstream字节流信息,转成字符串形式,并解析,这里的解析比较简单,仅仅获取uri(统一资源标识符)信息;
 5.处理响应:根据解析出来的uri信息,从web_root目录中寻找请求的资源资源文件, 读取资源文件,并将其写入到outputstream字节流中;
 6.关闭socket对象;
 7.转到步骤2,继续等待连接请求; 

二、代码实现

 服务器实现: 

package ex01.pyrmont;

import java.net.socket;
import java.net.serversocket;
import java.net.inetaddress;
import java.io.inputstream;
import java.io.outputstream;
import java.io.ioexception;
import java.io.file;

public class httpserver {

 /**
 * web_root是html和其它文件存放的目录. 这里的web_root为工作目录下的webroot目录
 */
 public static final string web_root = system.getproperty("user.dir") + file.separator + "webroot";

 // 关闭服务命令
 private static final string shutdown_command = "/shutdown";

 public static void main(string[] args) {
 httpserver server = new httpserver();
 //等待连接请求
 server.await();
 }

 public void await() {
 serversocket serversocket = null;
 int port = 8080;
 try {
  //服务器套接字对象
  serversocket = new serversocket(port, 1, inetaddress.getbyname("127.0.0.1"));
 } catch (ioexception e) {
  e.printstacktrace();
  system.exit(1);
 }

 // 循环等待一个请求
 while (true) {
  socket socket = null;
  inputstream input = null;
  outputstream output = null;
  try {
  //等待连接,连接成功后,返回一个socket对象
  socket = serversocket.accept();
  input = socket.getinputstream();
  output = socket.getoutputstream();

  // 创建request对象并解析
  request request = new request(input);
  request.parse();
  // 检查是否是关闭服务命令
  if (request.geturi().equals(shutdown_command)) {
   break;
  }

  // 创建 response 对象
  response response = new response(output);
  response.setrequest(request);
  response.sendstaticresource();

  // 关闭 socket 对象
  socket.close();
  
  } catch (exception e) {
  e.printstacktrace();
  continue;
  }
 }
 }
}

request类: 

package ex01.pyrmont;

import java.io.inputstream;
import java.io.ioexception;

public class request {

 private inputstream input;
 private string uri;

 public request(inputstream input) {
 this.input = input;
 }

 //从inputstream中读取request信息,并从request中获取uri值
 public void parse() {
 stringbuffer request = new stringbuffer(2048);
 int i;
 byte[] buffer = new byte[2048];
 try {
  i = input.read(buffer);
 } catch (ioexception e) {
  e.printstacktrace();
  i = -1;
 }
 for (int j = 0; j < i; j++) {
  request.append((char) buffer[j]);
 }
 system.out.print(request.tostring());
 uri = parseuri(request.tostring());
 }

 /**
 * 
 * requeststring形式如下:
 * get /index.html http/1.1
 * host: localhost:8080
 * connection: keep-alive
 * cache-control: max-age=0
 * ...
 * 该函数目的就是为了获取/index.html字符串
 */
 private string parseuri(string requeststring) {
 int index1, index2;
 index1 = requeststring.indexof(' ');
 if (index1 != -1) {
  index2 = requeststring.indexof(' ', index1 + 1);
  if (index2 > index1)
  return requeststring.substring(index1 + 1, index2);
 }
 return null;
 }

 public string geturi() {
 return uri;
 }

}

response类:

 package ex01.pyrmont;

import java.io.outputstream;
import java.io.ioexception;
import java.io.fileinputstream;
import java.io.file;

/*
 http response = status-line
 *(( general-header | response-header | entity-header ) crlf)
 crlf
 [ message-body ]
 status-line = http-version sp status-code sp reason-phrase crlf
*/

public class response {

 private static final int buffer_size = 1024;
 request request;
 outputstream output;

 public response(outputstream output) {
 this.output = output;
 }

 public void setrequest(request request) {
 this.request = request;
 }

 public void sendstaticresource() throws ioexception {
 byte[] bytes = new byte[buffer_size];
 fileinputstream fis = null;
 try {
  //将web文件写入到outputstream字节流中
  file file = new file(httpserver.web_root, request.geturi());
  if (file.exists()) {
  fis = new fileinputstream(file);
  int ch = fis.read(bytes, 0, buffer_size);
  while (ch != -1) {
   output.write(bytes, 0, ch);
   ch = fis.read(bytes, 0, buffer_size);
  }
  } else {
  // file not found
  string errormessage = "http/1.1 404 file not found\r\n" + "content-type: text/html\r\n"
   + "content-length: 23\r\n" + "\r\n" + "<h1>file not found</h1>";
  output.write(errormessage.getbytes());
  }
 } catch (exception e) {
  // thrown if cannot instantiate a file object
  system.out.println(e.tostring());
 } finally {
  if (fis != null)
  fis.close();
 }
 }
}

三、结果测试

访问存在的资源文件(注意存放在工程目录的webroot文件夹里):

简单实现Java web服务器

访问不存在的资源文件:

简单实现Java web服务器

关闭服务器:

简单实现Java web服务器

参考资料:《深入剖析tomcat》

@author   风一样的码农

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。