一、服务器简单实现
没有很多多余的逻辑,目前只是完成了服务器处理html的地址解析,其他头部没有去实现。这只是个demo。(如果要测试,请输入工程路径)
public class TestServer {
public static void main(String[] args) throws IOException {
//开始
start();
}
public static void start() {
//传入web工程路径(请输入工程路径)
String webRoot = "";
try {
start(webRoot);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void start(String webRoot) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
String address = "";
while (true) {
//解析浏览器
address = resolveFromBrowse(serverSocket);
//解析完传输数据
outputToBrowse(webRoot, address, serverSocket);
}
}
//从浏览器中解析
private static String resolveFromBrowse(ServerSocket serverSocket) throws IOException {
Socket inputSocket = serverSocket.accept();
InputStream inputSocketStream = inputSocket.getInputStream();
String netAddress = "";
try {
byte[] inputSocketBytes = new byte[1024];
int inputSocketLen = 0;
netAddress = "";
if ((inputSocketLen = inputSocketStream.read(inputSocketBytes)) != -1) {
String s = new String(inputSocketBytes, 0, inputSocketLen);
int i = s.indexOf(" ");
int i1 = s.indexOf(" ", i + 1);
netAddress = s.substring(i + 1, i1);
}
} finally {
inputSocketStream.close();
inputSocket.close();
}
return netAddress;
}
//传输到浏览器
public static void outputToBrowse(String webRoot, String address, ServerSocket serverSocket) throws IOException {
Socket outputSocket = null;
OutputStream outputStream = null;
InputStream outputSocketStream = null;
//先输出头部
try {
outputSocket = serverSocket.accept();
outputStream = outputSocket.getOutputStream();
byte[] bytes = ("HTTP/1.1 200 OK" +
" Content-Type:text/html \n\n").getBytes(StandardCharsets.UTF_8);
outputStream.write(bytes);
File fileExist = new File(webRoot + address);
//判断传入的地址是否有效,有效的话就返回给到浏览器,如果没有效,那么放过
if (address.startsWith("/") && address.length() > 1 && fileExist.exists()) {
outputSocketStream = Files.newInputStream(fileExist.toPath());
byte[] outputSocketbytes = new byte[1024];
int outputsocketLen = 0;
while ((outputsocketLen = outputSocketStream.read(outputSocketbytes)) != -1) {
outputStream.write(outputSocketbytes, 0, outputsocketLen);
}
}
} finally {
if (outputStream != null) {
outputStream.close();
}
if (outputSocket != null) {
outputSocket.close();
}
if (outputSocketStream != null) {
outputSocketStream.close();
}
}
}
}
效果: