Java 实现简单静态资源Web服务器的示例
需求
有时候我们想快速通过http访问本地的一些资源,但是安装一些web服务器又很费时和浪费资源,而且也不是长期使用的。
这时候我们可以启动一个小型的java服务器,快速实现一个http的静态资源web服务器。
难点
其实没什么难点,主要是注意请求头和返回头的处理。然后将请求的文件以流的方式读入返回outputstream即可。
代码
直接上代码吧~
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.net.InetAddress;
importjava.net.ServerSocket;
importjava.net.Socket;
importjava.nio.file.Files;
importjava.nio.file.Path;
importjava.nio.file.Paths;
publicclassResourceWebServer{
privatestaticfinalintSERVER_PORT=8888;
privatestaticfinalintMAX_CONNECTION_LENGTH=1;
publicstaticvoidmain(String[]args)throwsIOException{
log("======服务器启动=====");
ResourceWebServerserver=newResourceWebServer();
server.startServer();
}
publicvoidstartServer()throwsIOException{
ServerSocketserverSocket=newServerSocket(SERVER_PORT,MAX_CONNECTION_LENGTH,InetAddress.getByName("localhost"));
log("======准备接收请求=====");
while(true){
Socketsocket=serverSocket.accept();
try(InputStreaminputStream=socket.getInputStream();
OutputStreamoutputStream=socket.getOutputStream()){
StringrequestUri=getRequestUri(inputStream);
log("请求文件:"+requestUri);
writeHeaders(outputStream);
Pathpath=Paths.get(getClass().getClassLoader().getResource(requestUri.substring(1)).toURI());
Files.copy(path,outputStream);
}catch(Exceptione){
log("发生错误啦!");
e.printStackTrace();
}
}
}
privatevoidwriteHeaders(OutputStreamoutputStream)throwsIOException{
//必须包含返回头,否则浏览器不识别
outputStream.write("HTTP/1.1200OK\r\n".getBytes());
//一个\r\n代表换行添加新的头,2次\r\n代表头结束
outputStream.write("Content-Type:text/html\r\n\r\n".getBytes());
}
privateStringgetRequestUri(InputStreaminputStream)throwsIOException{
StringBuilderstringBuilder=newStringBuilder(2048);
byte[]buffer=newbyte[2048];
intsize=inputStream.read(buffer);
for(inti=0;i<size;i++){
stringBuilder.append((char)buffer[i]);
}
StringrequestUri=stringBuilder.toString();
//此时的uri还包含了请求头等信息,需要去掉
//GET/index.htmlHTTP/1.1...
intindex1,index2;
index1=requestUri.indexOf("");
if(index1!=-1){
index2=requestUri.indexOf("",index1+1);
if(index2>index1){
returnrequestUri.substring(index1+1,index2);
}
}
return"";
}
privatestaticvoidlog(Objectobject){
System.out.println(object);
}
}
接下来,就可以在resource文件下放入静态资源啦,比如放一个index.html
然后启动,打开浏览器输入http://localhost:8888/index.html就能看到结果了!
以上就是Java实现简单静态资源Web服务器的示例的详细内容,更多关于java实现web服务器的资料请关注毛票票其它相关文章!