Hello Web Server Web Server没有你想象的那么难实现(当然要实现一个好的Java Web Server还是很有难度的)。你只要明白基本的HTTP
协议,TCP
编程和IO
知识。当然,你也要会最简单的HTML
代码。
我们先来一个屌丝版,这个屌丝版能显示Hello Web Server
package exec.network.webserver;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleHttpServer {
private final static int TCP_PORT = 9090;
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(TCP_PORT);
Socket socket = ss.accept();
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String buffer = null;
while ((buffer = br.readLine()) != null && !s.equals("")) {
System.out.println(buffer);
}BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
bw.write("HTTP/1.1 200 OK\n");
bw.write("Content-Type: text/html;
charset=UTF-8\n\n");
bw.write("\n" + "\n" + "first page - 锐客网 \n"
+ "\n" + "\n" + "Hello Web Server!\n"
+ "\n" + "\n");
bw.flush();
bw.close();
br.close();
socket.close();
ss.close();
}
}
运行这个程序,然后再浏览器里敲:
http://localhost:9090/
,页面上会出现一个大大的Hello Web Server
。然后,就没有然后了……静态网页版 看了上面的程序,你可能都会说,太屌丝了,不行,继续。
【使用Java实现一个最简单的Web Server】我们来加强这个Web Server。
准备示例的静态页面文件 准备一个
webroot
文件夹,里面放个index.htm
文件,再准备一个01.jpg
文件,作为图片放进去。这个是我们准备的index.htm
,图片就不展示了。
Document - 锐客网
HTTP SERVER
Where there is a will, there is a way.
文章图片
准备HttpServer和Request,Response程序
- HttpServer
package exec.network.webserver;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class HttpServer {
private static final int SERVER_PORT = 9090;
public static final String WEB_ROOT = System.getProperty("user.dir")
+ File.separator + "webroot";
private static final String SHUTDOWN_COMMAND = "/QUIT";
public static void main(String[] args) {
HttpServer server = new HttpServer();
server.await();
}public void await() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(SERVER_PORT);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}while(true) {
Socket socket = null;
InputStream input = null;
OutputStream output = null;
try {
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();
}
}
}}
- Request
package exec.network.webserver;
import java.io.InputStream;
public class Request {
private final static int BUFFER_SIZE = 1024;
private InputStream input;
private String uri;
public Request(InputStream input) {
this.input = input;
}public void parse() {
StringBuffer request = new StringBuffer();
int readLength;
byte[] buffer = new byte[BUFFER_SIZE];
try {
readLength = input.read(buffer);
} catch (Exception e) {
e.printStackTrace();
readLength = -1;
}
for(int i = 0;
i < readLength;
i++) {
request.append((char)buffer[i]);
}
System.out.print(request.toString());
uri = parseUri(request.toString());
}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 exec.network.webserver;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
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[] buffer = new byte[BUFFER_SIZE];
FileInputStream fis = null;
try {
File file = new File(
HttpServer.WEB_ROOT, request.getUri());
if(file.exists()) {
output.write("HTTP/1.1 200 OK\n".getBytes());
output.write("Content-Type: text/html;
charset=UTF-8\n\n".getBytes());
fis = new FileInputStream(file);
int readLength;
while((readLength = fis.read(buffer, 0, BUFFER_SIZE)) > 0 ) {
output.write(buffer, 0, readLength);
}
}
else {
String errMsg = "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(errMsg.getBytes());
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if(fis != null) {
fis.close();
}
}
}
}
好了,最简单的Web Server我们已经用Java实现了,简单吧。
参考资料 http://www.cnblogs.com/chenpi/p/5602171.html
推荐阅读
- Java|Java基础——数组
- 人工智能|干货!人体姿态估计与运动预测
- java简介|Java是什么(Java能用来干什么?)
- Java|规范的打印日志
- Linux|109 个实用 shell 脚本
- 程序员|【高级Java架构师系统学习】毕业一年萌新的Java大厂面经,最新整理
- Spring注解驱动第十讲--@Autowired使用
- SqlServer|sql server的UPDLOCK、HOLDLOCK试验
- jvm|【JVM】JVM08(java内存模型解析[JMM])
- 技术|为参加2021年蓝桥杯Java软件开发大学B组细心整理常见基础知识、搜索和常用算法解析例题(持续更新...)