0

我正在关注此链接以在同一端口上运行套接字和 sslsocket。请检查以下代码以获取相同的端口。

private void startServer(int port) {
    try {
        ServerSocketFactory ssf = ServerSocketFactory.getDefault();
        ServerSocket serverSocket = ssf.createServerSocket();
        serverSocket.bind(new InetSocketAddress("127.0.0.1", port));
        serverSocket.setReuseAddress(true);

        SSLContext sslContext = SslUtil.createSSLContext(this);
        SSLSocketFactory sslSf = sslContext.getSocketFactory();
        while (true) {
            try {
                Socket client = serverSocket.accept();
                SSLSocket sslSocket = (SSLSocket) sslSf.createSocket(client, client.getInetAddress().getHostAddress(),
                        client.getPort(), false);
                sslSocket.setUseClientMode(false);

                boolean isSecure = false;
                String _url = "http://127.0.0.1:" + port + "/";
                String protocol = sslSocket.getSession().getProtocol();
                if (protocol != null && protocol.contains("TLS")) {
                    _url = "https://127.0.0.1:" + port + "/";
                    isSecure = true;
                }
                if (isSecure) {
                    executorService.execute(new HttpProcessor(sslSocket, _url, ctx));
                } else {
                    executorService.execute(new HttpProcessor(client, _url, ctx));
                }
            } catch (Exception ex) {
                serverSocket.close();
                Log.e("EX:", ex.toString());
                findPort();
                break;
            }
        }
    } catch (Exception e) {
        Log.e("Error:p1:", e.toString());
    }

}

此代码在 android 版本 6.0 (Marshmallow) 之前运行良好。但是当我在 android 7.0 及更高版本上运行此代码时,Https 工作正常但 Http 不工作。

这行“ String protocol = sslSocket.getSession().getProtocol(); ”在调用http请求时关闭连接。

有没有其他方法可以实现这一目标?

如何在android中查找客户端请求是http还是https sslSocket?

谢谢

4

0 回答 0