如何修复java httpsserver中数据包偶尔延迟的网络问题

np8igboo  于 2021-07-07  发布在  Java
关注(0)|答案(0)|浏览(186)

我用java制作了一个HTTPSWeb服务器,但是我遇到了这样的问题:发送第二个请求需要很多时间。老实说,我不知道问题出在哪里。我测试了从服务器读取数据并发送数据需要多长时间,最长50毫秒(当它是一个大图像时),对于一个简单的html或css文件通常需要4毫秒,所以这应该不是问题所在。
代码:
主要的

public class Main {
    public static Configuration conf;

    public static void main(String[] args) {

        ConfigurationManager.getInstance().loadConfigurationFile("http.json");
        conf = ConfigurationManager.getInstance().getCurrentConfiguration();

        SimpleHttpsServer httpsServer = new SimpleHttpsServer();
        httpsServer.Start(conf.getPasscert(), conf.getHost(), 443);

    }
}

SimpleHTTPS服务器

public class SimpleHttpsServer {
    private HttpsServer server;
    private static String protocol = "TLS";

    public void Start(String pass, String address, int port) {
        try {
            String keystoreFilename = "./" + address + ".keystore";
            char[] storepass = pass.toCharArray();
            char[] keypass = pass.toCharArray();
            FileInputStream fIn = new FileInputStream(keystoreFilename);
            KeyStore keystore = KeyStore.getInstance("JKS");
            keystore.load(fIn, storepass);

            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(keystore, keypass);

            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            tmf.init(keystore);

            server = HttpsServer.create(new InetSocketAddress(address, port), 0);

            SSLContext sslContext = SSLContext.getInstance(protocol);
            sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
            server.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
                public void configure(HttpsParameters params) {
                    try {
                        SSLContext c = SSLContext.getDefault();
                        SSLEngine engine = c.createSSLEngine();
                        params.setNeedClientAuth(false);
                        params.setCipherSuites(engine.getEnabledCipherSuites());
                        params.setProtocols(engine.getEnabledProtocols());

                        SSLParameters defaultSSLParameters = c.getDefaultSSLParameters();
                        params.setSSLParameters(defaultSSLParameters);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        System.out.println("Failed to create HTTPS server");
                    }
                }
            });

            System.out.println("HTTPS server started at " + address + ":" + port);
            server.createContext("/", new HandlersHTTPS.RootHandler());
            server.setExecutor(null);
            server.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        }
    }
}

把手shttps

public class HandlersHTTPS {
    public static class RootHandler implements HttpHandler {

        public void handle(HttpExchange he) throws IOException {

            String path = he.getRequestURI().toString();
            String host = he.getRequestHeaders().getFirst("Host");

            String subHost = host.substring(0, host.length() - Main.conf.getHost().length());
            if(subHost.length() > 0) {
                subHost = subHost.substring(0, subHost.length() - 1);
            } else {
                subHost = "www";
            }

            String filePath = Main.conf.getWebroot() + "/" + subHost;

            if(path.equals("/")) {
                if(new File(filePath + "/index.html").exists()) {
                    filePath += "/index.html";
                }
            }

            String ending = GetEnding(path);
            if(!ending.isEmpty()) {
                filePath += path;
            } else {
                if(new File(filePath + ".html").exists()) {
                    filePath += ".html";
                }
            }

            File file = new File(filePath);
            if(file.exists()) {
                if(!file.isDirectory()) {
                    if(isImage(file)) {
                        InputStream is = new FileInputStream(file);
                        byte[] bytes = IOUtils.toByteArray(is);
                        is.close();

                        Headers h = he.getResponseHeaders();
                        h.add("content-type", GetImageContentType(file));

                        he.sendResponseHeaders(200, bytes.length);
                        OutputStream os = he.getResponseBody();
                        os.write(bytes);
                        os.close();
                    } else {
                        String data = "";
                        BufferedReader br = new BufferedReader(new FileReader(file));
                        String st;
                        while ((st = br.readLine()) != null) {
                            data += st;
                        }
                        br.close();
                        int length = data.getBytes().length;

                        he.sendResponseHeaders(200, length);
                        OutputStream os = he.getResponseBody();
                        os.write(data.getBytes());
                        os.close();
                    }
                    return;
                }
            }

            he.sendResponseHeaders(404, 0);
            OutputStream os = he.getResponseBody();
            os.close();
        }

        private String GetEnding(String s) {
            String ending = "";
            int index = s.lastIndexOf('.');
            if(index != -1) {
                ending = s.substring(index);
            }
            return ending;
        }

        private boolean isImage(File file) {
            String mimetype = new MimetypesFileTypeMap().getContentType(file);
            String type = mimetype.split("/")[0];
            return type.equals("image");
        }

        public String GetImageContentType(File file) {
            String name = file.getName();
            return GetImageContentType(name);
        }

        public String GetImageContentType(String name) {
            if(!name.contains(".")) {
                return null;
            }
            String ending = GetEnding(name).toLowerCase();
            if(ending.equals("jpg") || ending.equals("jpeg") || ending.equals("jfif") || ending.equals("pjpeg") || ending.equals("pjp")) {
                return "image/jpeg";
            } else if(ending.equals("ico") || ending.equals("cur")) {
                return "image/x-icon";
            } else if(ending.equals("tif") || ending.equals("tiff")) {
                return "image/tiff";
            } else if(ending.equals("svg")) {
                return "image/svg+xml";
            } else if(ending.equals("")) {
                return "image/" + ending;
            }
            return "image/*";
        }
    }
}

浏览器网络选项卡中的图像:
“网络”选项卡
长时间停顿的细节1
长停顿2的细节
如果你有任何关于我做错了什么的信息,或者你认为我应该补充更多的信息,请告诉我。提前感谢您的帮助!

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题