问题
I'm trying to create simple web server using java sockets which should support both http & https. But i can acheive only one at a time. I need to logic which supports both http @ port 80 & https @ port 443 at same time.
This is the sample code for HTTPS Server using sslsocket. We can acheive HTTP Server using simple ServerSocket.
public class HttpsServer {
public static void main(String[] args) {
try {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new FileInputStream("/opt/p12file.p12"), "p12pass".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, "p12pass".toCharArray());
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(kmf.getKeyManagers(), null, null);
SSLServerSocketFactory ssf = sc.getServerSocketFactory();
SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(8080);
while (true) {
SSLSocket c = (SSLSocket) s.accept();
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));
w.write("HTTP/1.0 200 OK");
w.newLine();
w.write("Content-Type: text/html");
w.newLine();
w.newLine();
w.write("<html><body><h1>Https Server Works</h1></body></html>");
w.newLine();
w.flush();
w.close();
c.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Can anyone help me please??
回答1:
How make SSL server socket support both http & https in java?
You can't. HTTP is plaintext, which SSLServerSocket
cannot support.
I'm trying to create simple web server using java sockets which should support both http & https. But I can achieve only one at a time. I need to logic which supports both http @ port 80 & https @ port 443 at same time.
You need:
- a plaintext
ServerSocket
listening at 80 - an
SSLServerSocket
listening at 443 - an accept-loop thread for each of these
- a connection thread per accepted socket.
You will never ever get it done inside a static main()
method. I suggest you read the 'Custom Networking' section of the Java Tutorial, and then the JSSE Reference Guide.
You also of course need to take a really good look at RFC 2616 HTTP 1.1. It is extremely non-trivial to implement correctly.
As suggested in comments, you should really use something off-the-shelf.
回答2:
You have two options:
Use two different ports, one for http and one for https.
SSL Hello detection / Port unification:
In HTTP and HTTPS the client is expected to talk first. So the server can use this to detect the protocol the client is expecting:
- if the client sends a TLS ClientHello, then proceed with a TLS handshake;
- if a plain HTTP request is sent instead, then handle the request as it is.
More information:
Can a Java server accept both SSL and plaintext connections on one port?
Is it possible to change plain socket to SSLSocket?
来源:https://stackoverflow.com/questions/30498206/how-make-ssl-server-socket-support-both-http-https-in-java