致命温柔,简略完成Java web服务器,成都职业技术学院

原文地址:https://www.jb51.net/article/86990.htm

作者:风相同的码农

一个简略的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;丧命温顺,简略完结Java web服务器,成都作业技术学院

public class HttpServer {

/**
* WEB_ROOT是HTML和其它文件寄存的目录. 这儿的WEB_ROOT为作业目录下的webroot目录
*/
public static final String WEB_ROOT = System丧命温顺,简略完结Java web服务器,成都作业技术学院.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.printStackT那路或多race();
System.exit(1);
}

// 循环等候一个恳求
while (true) {
Socket socket = null;
InputStream input = null;
OutputdecideStream output丧命温顺,简略完结Java web服务器,成都作业技术学院 = 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);
}丧命温顺,简略完结Java web服务器,成都作业技术学院 catch (nothingIOException e) {
e.printStackTrace(91撸);
i = -1;
}
for (int j = 0; j < i; j++) {
req桐城uest.append((char) buffer[j]);
}
System.out.print(request.toString());
uri = parseUri(request.toString());
}

/**
*
* requestString方式如下:
* GET /index.html HTTP/1.1
* Host:丧命温顺,简略完结Java web服务器,成都作业技术学院 localhost:8080
* Connection: k放大镜简笔画eep-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丧命温顺,简略完结Java web服务器,成都作业技术学院)
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.FilcompetitioneInputStream;
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丧命温顺,简略完结Java web服务器,成都作业技术学院 errorMe目土土ssage = "HTTP/1.1 404 File Not Found\r\n" + "Content-Type: text/html\r\n"
+ "Content-Length: 23\r\n" + "\r\n" + "

File Not Found

";
output.write(errorMessage.getBytes());
}
} catch (Exception e) {
// thrown i虫f cannot instantiate a File 彤object
System.out.println(唐装e.toString());
} finally {
if (fis != null)
fis.close();
}
}
}

三、成果测试

拜访存在的资源文件(留意寄存在工程目录的webroot文件夹里):

拜访不存在的资源文件:

封闭服务器: