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??
You can't. HTTP is plaintext, which
SSLServerSocket
cannot support.You need:
ServerSocket
listening at 80SSLServerSocket
listening at 443You 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.
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:
More information:
Can a Java server accept both SSL and plaintext connections on one port?
Is it possible to change plain socket to SSLSocket?