📄 httpservice.java
字号:
package com.softeem.HttpServer.session;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class HttpService implements Runnable {
// 资源的具体路径
private static final String COMMAND = "GET";
private static final int MAX_LENGTH = 1024;
private static final String PARTION = " ";
private Socket socket;
// 使用通过构造器传过来的socket类(这个类一定对应的有一个客户存在)
public HttpService(Socket socket) {
this.socket = socket;
}
// http://192.168.23.61:80/index.html
// GET /index.html HTTP/1.1
// Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,
// application/x-shockwave-flash, application/vnd.ms-excel,
// application/vnd.ms-powerpoint, application/msword, */*
// Accept-Language: zh-cn
// Accept-Encoding: gzip, deflate
// User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET
// CLR 2.0.50727)
// Host: 192.168.23.61
// Connection: Keep-Alive
public void run() {
try {
// 从主线程传递过来的Socket(相当于客户端)读取客户要请求的资源转变为字符流
BufferedReader br = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) { // 读取字符流中包含的客户端的请求的资源
System.out.println(line);
if (line.length() < 3) // 判断读取的资源不要小于HTTP中GET指令的长度
break;
doGet(line);// 用line来获得请求的资源
}
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doGet(String line) {
String[] strs = line.split(PARTION);// 对HTTP传过来的指令进行分割
String command = strs[0];// HTTP协议发送的具体指令
String fileName = null;
if (command.equalsIgnoreCase(COMMAND)) {// 判断是否为GET指令
if (strs[1].length() <= 1) // 如果没有请求的资源获得默认的页面
// 动态获取客户端的访问的指定的资源
fileName = SystemConfig.getSystemConfig().getDefaultFile();
else
fileName = strs[1].substring(1);// 截取HTTP协议传过来的指令的资源名称
// F:\\JAVA23\\files\\index.html
File file = new File(SystemConfig.getSystemConfig()
.getResourcePath()
+ fileName);// 获得本地资源库中具体资源的路径名
try {
InputStream in = new FileInputStream(file);// 文件输入流
byte[] buff = new byte[MAX_LENGTH];
// 获得网络流的本地文件流 网络输出流
OutputStream out = socket.getOutputStream();
int length = 0;
// 实现边读边写的功能 并把文件流转换了网络流
while ((length = in.read(buff)) != -1) {
// 把从本地得到的资源传给客户端
out.write(buff, 0, length);
}
out.close();
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -