服務器端服務器
System.out.println("等待客戶端鏈接..."); File keyFile=new File("C:/Users/mu/Desktop/mu.p12"); InputStream stream=new FileInputStream(keyFile); char[] password="123456".toCharArray(); //KeyStore用於存放證書,建立對象時 指定交換數字證書的加密標準 KeyStore keyStore=KeyStore.getInstance("pkcs12"); //KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(stream, password); stream.close(); //KeyManager選擇證書證實本身的身份 KeyManagerFactory keyManagerFactory=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore,password); KeyManager[] keyManagers=keyManagerFactory.getKeyManagers(); //TrustManager決定是否信任對方的證書 TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); TrustManager[] trustManagers=trustManagerFactory.getTrustManagers(); SSLContext context=SSLContext.getInstance("SSL"); context.init(keyManagers, trustManagers, null); SSLServerSocketFactory factory=context.getServerSocketFactory(); SSLServerSocket serverSocket=(SSLServerSocket)factory.createServerSocket(3344); SSLSocket socket=(SSLSocket)serverSocket.accept(); System.out.println("有客戶端鏈接"); System.out.println("向客戶端輸出信息"); OutputStream outputStream=socket.getOutputStream(); BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(outputStream)); writer.write("hello world\r\n"); writer.write("\r\n"); writer.flush(); System.out.println("輸出結束"); socket.close(); serverSocket.close();
客戶端socket
System.out.println("準備鏈接服務端"); File keyFile=new File("C:/Users/mu/Desktop/mu.p12"); InputStream stream=new FileInputStream(keyFile); char[] password="123456".toCharArray(); //指定交換數字證書的加密標準 KeyStore keyStore= KeyStore.getInstance("pkcs12");//KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(stream, password); stream.close(); //TrustManager決定是否信任對方的證書 TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); TrustManager[] trustManagers=trustManagerFactory.getTrustManagers(); SSLContext context=SSLContext.getInstance("SSL"); context.init(null, trustManagers, null); SSLSocketFactory factory=context.getSocketFactory(); SSLSocket socket=(SSLSocket) factory.createSocket("localhost", 3344); InputStream inputStream=socket.getInputStream(); BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream)); String str=null; while ((str=reader.readLine())!=null) { if(str.equals("")) break; System.out.println(str); } socket.close();