利用Java Socket编写一个简单的Web服务器,具体如下:
(1)、使用 ServerSocket 监听某一端口,然后等待连接获取 Socket对象;
(2)、创建一个类 HttpServer 继承 java.lang.Thread 类,重写 run()方法,执行浏览器请求;
(3)、获得浏览器请求,解析资源文件路径;
(4)、读取资源文件,响应给浏览器;
(5)、浏览器地址栏输入: http://localhost:8000/index.html;
源码
package com;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class webserver {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8000);
while(true){
//服务器套接字
Socket socket = serverSocket.accept();
new HttpServer(socket).start(); {
};
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com;
import java.io.*;
import java.net.Socket;
public class HttpServer extends Thread {
private Socket socket;
public HttpServer(Socket socket) {
this.socket=socket;
}
@Override
public void run() {
super.run();
String filePath = "/index.html";
File file=new File(System.getProperty("user.dir")+filePath);
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
System.out.println("reader :" + reader);
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\r\n");
}
StringBuffer result = new StringBuffer();
result.append("HTTP /1.1 200 ok \r\n");
result.append("Content-Type:text/html \r\n");
result.append("Content-Length:" + file.length() + "\r\n");
result.append("\r\n" + sb.toString());
OutputStream out=socket.getOutputStream();
out.write(result.toString().getBytes());
System.out.println(result.toString());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}