工具类
package com.briup.webServer.bean;
import java.io.*;
import java.net.Socket;
public class ServerThread implements Runnable{
private Socket socket;
public ServerThread(Socket socket){
this.socket=socket;
}
public void run(){
// 1.接收客户端请求
// 2.解析客户端请求 拿到请求的资源路径
String url = null;
try {
url = getUrl();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("请求资源路径:"+url);
// 3.根据资源路径寻找对应的文件
// 4.根据文件存在与否给客户端返回响应
try {
sendResponse(url);
} catch (IOException e) {
e.printStackTrace();
}
}
private String getUrl() throws IOException {
BufferedReader br =new BufferedReader(new InputStreamReader(socket.getInputStream()));
String requestLine = br.readLine();
System.out.println("请求行:" + requestLine);
String[] array = requestLine.split(" ");
return array[1];
}
private void sendResponse(String url) throws IOException {
//根据文件路径寻找对应的文件
//根据文件存在与否给客户端返回响应
PrintStream ps = null;
BufferedInputStream bis = null;
try {
ps = new PrintStream(socket.getOutputStream());
File file = new File("F:\\Project",url);
boolean flag = file.exists();
String line = null;
if (flag){
line = "HTTP/1.1 200 OK";
if ("/".equals(url)){
file = new File("F:\\Project", "welcome.html");
}
}else{
line= "HTTP/1.1 404 NotFound";
file = new File("F:\\Project", "error.html");
}
ps.println(line);
ps.println();
bis = new BufferedInputStream(new FileInputStream(file));
byte[] bytes = new byte[1024];
int bsize;
while ((bsize = bis.read(bytes)) != -1) {
// 将文件中的数据 发送给浏览器
ps.write(bytes, 0, bsize);
}
ps.flush();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (ps != null)
ps.close();
if (bis != null)
bis.close();
}
}
}
启动类
package com.briup.webServer.server;
import com.briup.webServer.bean.ServerThread;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerMainPro {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(9998);
System.out.println("你好,服务器9998即将启动");
while (true){
Socket socket = server.accept();
System.out.println("有客户端连接"+socket);
ServerThread thread = new ServerThread(socket);
new Thread(thread).start();
}
}
}