how2j.cn

下载区
文件名 文件大小
请先登录 1k
增值内容 1k
1k
请先登录 3m
增值内容 3m
3m
请先登录 10m
增值内容 10m
10m

6分54秒
本视频采用html5方式播放,如无法正常播放,请将浏览器升级至最新版本,推荐火狐,chrome,360浏览器。 如果装有迅雷,播放视频呈现直接下载状态,请调整 迅雷系统设置-基本设置-启动-监视全部浏览器 (去掉这个选项)。 chrome 的 视频下载插件会影响播放,如 IDM 等,请关闭或者切换其他浏览器

步骤 1 : 拓扑图点亮   
步骤 2 : 二进制文件   
步骤 3 : Response   
步骤 4 : Server   
步骤 5 : etf.pdf logo.png   
步骤 6 : MiniBrowser   
步骤 7 : Request   
步骤 8 : TestTomcat   
步骤 9 : 比较可运行项目,快速定位问题   

增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
拓扑图点亮
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.http; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; public class Response { private StringWriter stringWriter; private PrintWriter writer; private String contentType; private byte[] body; public Response(){ this.stringWriter = new StringWriter(); this.writer = new PrintWriter(stringWriter); this.contentType = "text/html"; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public PrintWriter getWriter() { return writer; } public byte[] getBody() throws UnsupportedEncodingException { if(null==body) { String content = stringWriter.toString(); body = content.getBytes("utf-8"); } return body; } public void setBody(byte[] body) { this.body = body; } }
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.catalina; import cn.how2j.diytomcat.http.Request; import cn.how2j.diytomcat.http.Response; import cn.how2j.diytomcat.util.Constant; import cn.how2j.diytomcat.util.ThreadPoolUtil; import cn.how2j.diytomcat.util.WebXMLUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.thread.ThreadUtil; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.log.LogFactory; import cn.hutool.system.SystemUtil; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; public class Server { private Service service; public Server(){ this.service = new Service(this); } public void start(){ logJVM(); init(); } private void init() { try { int port = 18080; ServerSocket ss = new ServerSocket(port); while(true) { Socket s = ss.accept(); Runnable r = new Runnable(){ @Override public void run() { try { Request request = new Request(s,service); Response response = new Response(); String uri = request.getUri(); if(null==uri) return; System.out.println("uri:"+uri); Context context = request.getContext(); if("/500.html".equals(uri)){ throw new Exception("this is a deliberately created exception"); } if("/".equals(uri)) uri = WebXMLUtil.getWelcomeFile(request.getContext()); String fileName = StrUtil.removePrefix(uri, "/"); File file = FileUtil.file(context.getDocBase(),fileName); if(file.exists()){ String extName = FileUtil.extName(file); String mimeType = WebXMLUtil.getMimeType(extName); response.setContentType(mimeType); // String fileContent = FileUtil.readUtf8String(file); // response.getWriter().println(fileContent); byte body[] = FileUtil.readBytes(file); response.setBody(body); if(fileName.equals("timeConsume.html")){ ThreadUtil.sleep(1000); } } else{ handle404(s, uri); return; } handle200(s, response); } catch (Exception e) { LogFactory.get().error(e); handle500(s,e); } finally{ try { if(!s.isClosed()) s.close(); } catch (IOException e) { e.printStackTrace(); } } } }; ThreadPoolUtil.run(r); } } catch (IOException e) { LogFactory.get().error(e); e.printStackTrace(); } } private static void logJVM() { Map<String,String> infos = new LinkedHashMap<>(); infos.put("Server version", "How2J DiyTomcat/1.0.1"); infos.put("Server built", "2020-04-08 10:20:22"); infos.put("Server number", "1.0.1"); infos.put("OS Name\t", SystemUtil.get("os.name")); infos.put("OS Version", SystemUtil.get("os.version")); infos.put("Architecture", SystemUtil.get("os.arch")); infos.put("Java Home", SystemUtil.get("java.home")); infos.put("JVM Version", SystemUtil.get("java.runtime.version")); infos.put("JVM Vendor", SystemUtil.get("java.vm.specification.vendor")); Set<String> keys = infos.keySet(); for (String key : keys) { LogFactory.get().info(key+":\t\t" + infos.get(key)); } } private static void handle200(Socket s, Response response) throws IOException { String contentType = response.getContentType(); String headText = Constant.response_head_202; headText = StrUtil.format(headText, contentType); byte[] head = headText.getBytes(); byte[] body = response.getBody(); byte[] responseBytes = new byte[head.length + body.length]; ArrayUtil.copy(head, 0, responseBytes, 0, head.length); ArrayUtil.copy(body, 0, responseBytes, head.length, body.length); OutputStream os = s.getOutputStream(); os.write(responseBytes); } protected void handle404(Socket s, String uri) throws IOException { OutputStream os = s.getOutputStream(); String responseText = StrUtil.format(Constant.textFormat_404, uri, uri); responseText = Constant.response_head_404 + responseText; byte[] responseByte = responseText.getBytes("utf-8"); os.write(responseByte); } protected void handle500(Socket s, Exception e) { try { OutputStream os = s.getOutputStream(); StackTraceElement stes[] = e.getStackTrace(); StringBuffer sb = new StringBuffer(); sb.append(e.toString()); sb.append("\r\n"); for (StackTraceElement ste : stes) { sb.append("\t"); sb.append(ste.toString()); sb.append("\r\n"); } String msg = e.getMessage(); if (null != msg && msg.length() > 20) msg = msg.substring(0, 19); String text = StrUtil.format(Constant.textFormat_500, msg, e.toString(), sb.toString()); text = Constant.response_head_500 + text; byte[] responseBytes = text.getBytes("utf-8"); os.write(responseBytes); } catch (IOException e1) { e1.printStackTrace(); } } }
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.util; import java.io.*; import java.net.InetSocketAddress; import java.net.Socket; import java.net.URL; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import cn.hutool.core.convert.Convert; import cn.hutool.core.util.ZipUtil; import cn.hutool.http.HttpUtil; public class MiniBrowser { public static void main(String[] args) throws Exception { String url = "http://static.how2j.cn/diytomcat.html"; String contentString= getContentString(url,false); System.out.println(contentString); String httpString= getHttpString(url,false); System.out.println(httpString); } public static byte[] getContentBytes(String url) { return getContentBytes(url, false); } public static String getContentString(String url) { return getContentString(url,false); } public static String getContentString(String url, boolean gzip) { byte[] result = getContentBytes(url, gzip); if(null==result) return null; try { return new String(result,"utf-8").trim(); } catch (UnsupportedEncodingException e) { return null; } } public static byte[] getContentBytes(String url, boolean gzip) { byte[] response = getHttpBytes(url,gzip); byte[] doubleReturn = "\r\n\r\n".getBytes(); int pos = -1; for (int i = 0; i < response.length-doubleReturn.length; i++) { byte[] temp = Arrays.copyOfRange(response, i, i + doubleReturn.length); if(Arrays.equals(temp, doubleReturn)) { pos = i; break; } } if(-1==pos) return null; pos += doubleReturn.length; byte[] result = Arrays.copyOfRange(response, pos, response.length); return result; } public static String getHttpString(String url,boolean gzip) { byte[] bytes=getHttpBytes(url,gzip); return new String(bytes).trim(); } public static String getHttpString(String url) { return getHttpString(url,false); } public static byte[] getHttpBytes(String url,boolean gzip) { byte[] result = null; try { URL u = new URL(url); Socket client = new Socket(); int port = u.getPort(); if(-1==port) port = 80; InetSocketAddress inetSocketAddress = new InetSocketAddress(u.getHost(), port); client.connect(inetSocketAddress, 1000); Map<String,String> requestHeaders = new HashMap<>(); requestHeaders.put("Host", u.getHost()+":"+port); requestHeaders.put("Accept", "text/html"); requestHeaders.put("Connection", "close"); requestHeaders.put("User-Agent", "how2j mini brower / java1.8"); if(gzip) requestHeaders.put("Accept-Encoding", "gzip"); String path = u.getPath(); if(path.length()==0) path = "/"; String firstLine = "GET " + path + " HTTP/1.1\r\n"; StringBuffer httpRequestString = new StringBuffer(); httpRequestString.append(firstLine); Set<String> headers = requestHeaders.keySet(); for (String header : headers) { String headerLine = header + ":" + requestHeaders.get(header)+"\r\n"; httpRequestString.append(headerLine); } PrintWriter pWriter = new PrintWriter(client.getOutputStream(), true); pWriter.println(httpRequestString); InputStream is = client.getInputStream(); result = readBytes(is,true); client.close(); } catch (Exception e) { e.printStackTrace(); try { result = e.toString().getBytes("utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } } return result; } public static byte[] readBytes(InputStream is, boolean fully) throws IOException { int buffer_size = 1024; byte buffer[] = new byte[buffer_size]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while(true) { int length = is.read(buffer); if(-1==length) break; baos.write(buffer, 0, length); if(!fully && length!=buffer_size) break; } byte[] result =baos.toByteArray(); return result; } }
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.test; import cn.how2j.diytomcat.util.MiniBrowser; import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.TimeInterval; import cn.hutool.core.util.NetUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.ZipUtil; import cn.hutool.http.HttpUtil; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import sun.net.www.content.text.plain; import java.io.ByteArrayOutputStream; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class TestTomcat { private static int port = 18080; private static String ip = "127.0.0.1"; @BeforeClass public static void beforeClass() { //所有测试开始前看diy tomcat 是否已经启动了 if(NetUtil.isUsableLocalPort(port)) { System.err.println("请先启动 位于端口: " +port+ " 的diy tomcat,否则无法进行单元测试"); System.exit(1); } else { System.out.println("检测到 diy tomcat已经启动,开始进行单元测试"); } } @Test public void testHelloTomcat() { String html = getContentString("/"); Assert.assertEquals(html,"Hello DIY Tomcat from how2j.cn"); } @Test public void testTimeConsumeHtml() throws InterruptedException { ThreadPoolExecutor threadPool = new ThreadPoolExecutor(20, 20, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(10)); TimeInterval timeInterval = DateUtil.timer(); for(int i = 0; i<3; i++){ threadPool.execute(new Runnable(){ public void run() { getContentString("/timeConsume.html"); } }); } threadPool.shutdown(); threadPool.awaitTermination(1, TimeUnit.HOURS); long duration = timeInterval.intervalMs(); Assert.assertTrue(duration < 3000); } @Test public void testaIndex() { String html = getContentString("/a"); Assert.assertEquals(html,"Hello DIY Tomcat from index.html@a"); } @Test public void testbIndex() { String html = getContentString("/b/"); Assert.assertEquals(html,"Hello DIY Tomcat from index.html@b"); } @Test public void test404() { String response = getHttpString("/not_exist.html"); containAssert(response, "HTTP/1.1 404 Not Found"); } @Test public void test500() { String response = getHttpString("/500.html"); containAssert(response, "HTTP/1.1 500 Internal Server Error"); } @Test public void testaTxt() { String response = getHttpString("/a.txt"); containAssert(response, "Content-Type: text/plain"); } @Test public void testPNG() { byte[] bytes = getContentBytes("/logo.png"); int pngFileLength = 1672; Assert.assertEquals(pngFileLength, bytes.length); } @Test public void testPDF() { byte[] bytes = getContentBytes("/etf.pdf"); int pngFileLength = 3590775; Assert.assertEquals(pngFileLength, bytes.length); } private byte[] getContentBytes(String uri) { return getContentBytes(uri,false); } private byte[] getContentBytes(String uri,boolean gzip) { String url = StrUtil.format("http://{}:{}{}", ip,port,uri); return MiniBrowser.getContentBytes(url,false); } private String getContentString(String uri) { String url = StrUtil.format("http://{}:{}{}", ip,port,uri); String content = MiniBrowser.getContentString(url); return content; } private String getHttpString(String uri) { String url = StrUtil.format("http://{}:{}{}", ip,port,uri); String http = MiniBrowser.getHttpString(url); return http; } private void containAssert(String html, String string) { boolean match = StrUtil.containsAny(html, string); Assert.assertTrue(match); } }
步骤 9 :

比较可运行项目,快速定位问题

edit
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢


HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。


问答区域    
2022-07-08 浏览器下载报异常
冬瓜丶




前面也有人发过了,单元测试是没问题,但浏览器下载etf.pdf或者大点的文件就会报异常,如何解决?
 private static void handle200(Socket s, Response response) throws IOException {
        String contentType = response.getContentType();
        String headText = Constant.RESPONSE_HEAD_202;
        headText = StrUtil.format(headText, contentType);

        byte[] head = headText.getBytes();
        byte[] body = response.getBody();
        byte[] responseBytes = new byte[head.length + body.length];

        ArrayUtil.copy(head, 0, responseBytes, 0, head.length);
        ArrayUtil.copy(body, 0, responseBytes, head.length, body.length);

        OutputStream os = s.getOutputStream();
        os.write(responseBytes);
    }
java.net.SocketException: Connection reset by peer: socket write error
	at java.net.SocketOutputStream.socketWrite0(Native Method)
	at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
	at java.net.SocketOutputStream.write(SocketOutputStream.java:143)
	at com.dg.tomcat.catalina.Server.handle200(Server.java:159)
	at com.dg.tomcat.catalina.Server.lambda$init$0(Server.java:101)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)


1 个答案

how2j
答案时间:2022-08-01
我是用chrome没问题的,难道不同的浏览器处理不一样吗? 扣脑壳。。



回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到





2021-04-17 关于这个读取逻辑,站主是有两点是没说明白的。
chuancey




public static byte[] readBytes(InputStream is,boolean fully) throws IOException { int buffer_size = 1024; byte buffer[] = new byte[buffer_size]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while(true) { int length = is.read(buffer); if(length==-1) //当服务器使用readBytes函数时,因为浏览器默认使用长链接,不会主动关闭连接,所以服务器不会读取到-1,所以需要使用if(!fully&&length!=buffer_size)来退出读取,这里默认浏览器读取服务器的数据是1024,1024, ... <1024的这种情况(如果读到这没懂,别急,往下读) break; baos.write(buffer, 0, length); if(!fully&&length!=buffer_size) //1.这里当buffer_size!=length时说明,已经读到了末尾,即只剩小于1024字节的内容了(由于已经写过了),所以这里可以退出了。这种情况是针对fully=flase, 服务器发送给浏览器的数据的读取是1024,1024, ... <1024,但实际上,站主也考虑了另一种情况,服务器发送给浏览器的数据的读取是<1024,<2014,<1024,,,为了让这种情况能够正常运行,需要fully=true。结合上面所述,这里的问题在于:1.我们怎么能确定服务器发给浏览器的数据的读取是第一种情况还是第二种情况。2.为什么能确定浏览器读取服务器的数据是1024,1024, ... <1024的这种情况? break; } byte[] result=baos.toByteArray(); return result; }
   public static byte[] readBytes(InputStream is,boolean fully) throws IOException {
        int buffer_size = 1024;
        byte buffer[] = new byte[buffer_size];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while(true) {
            int length = is.read(buffer);
            if(length==-1) //当服务器使用readBytes函数时,因为浏览器默认使用长链接,不会主动关闭连接,所以服务器不会读取到-1,所以需要使用if(!fully&&length!=buffer_size)来退出读取,这里默认浏览器读取服务器的数据是1024,1024, ... <1024的这种情况(如果读到这没懂,别急,往下读)
                break;
            baos.write(buffer, 0, length); 
            if(!fully&&length!=buffer_size) //1.这里当buffer_size!=length时说明,已经读到了末尾,即只剩小于1024字节的内容了(由于已经写过了),所以这里可以退出了。这种情况是针对fully=flase, 服务器发送给浏览器的数据的读取是1024,1024, ... <1024,但实际上,站主也考虑了另一种情况,服务器发送给浏览器的数据的读取是<1024,<2014,<1024,,,为了让这种情况能够正常运行,需要fully=true。结合上面所述,这里的问题在于:1.我们怎么能确定服务器发给浏览器的数据的读取是第一种情况还是第二种情况。2.为什么能确定浏览器读取服务器的数据是1024,1024, ... <1024的这种情况?
                break;
        }
        byte[] result=baos.toByteArray();
        return result;
    }

							


2 个答案

黄文新
答案时间:2023-02-02
看完这块我也很纳闷这里的,浏览器应该会有相应的识别吧,如果默认长连接的话那肯定要false才行,如果true就会一直卡在哪里,但是false的话对于那些pdf文件就没办法完全读取。

how2j
答案时间:2021-04-21
其实这个地方我也有点不是很清晰,因为不同浏览器的做法是不一样的,同一个代码在 chrome 和 ie edge上表现不一样 。。。



回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到





2020-10-05 步骤七
2020-07-18 功能正常,但是服务器会报异常
2020-06-15 站长,为啥浏览器和服务器判断读取文件完毕的逻辑不一样?


提问太多,页面渲染太慢,为了加快渲染速度,本页最多只显示几条提问。还有 2 条以前的提问,请 点击查看

提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
关于 实践项目-DiyTomcat-二进制文件 的提问

尽量提供截图代码异常信息,有助于分析和解决问题。 也可进本站QQ群交流: 578362961
提问尽量提供完整的代码,环境描述,越是有利于问题的重现,您的问题越能更快得到解答。
对教程中代码有疑问,请提供是哪个步骤,哪一行有疑问,这样便于快速定位问题,提高问题得到解答的速度
在已经存在的几千个提问里,有相当大的比例,是因为使用了和站长不同版本的开发环境导致的,比如 jdk, eclpise, idea, mysql,tomcat 等等软件的版本不一致。
请使用和站长一样的版本,可以节约自己大量的学习时间。 站长把教学中用的软件版本整理了,都统一放在了这里, 方便大家下载: https://how2j.cn/k/helloworld/helloworld-version/1718.html

上传截图