1. 程式人生 > >java-websocket 服務端 開發中遇到的問題

java-websocket 服務端 開發中遇到的問題

一、

    由於專案需求,需要早android裝置上架一個websocket服務,可以供瀏覽器呼叫。但是移動裝置的ip是不固定的,也就是說到作為服務端,移動裝置並不能完全滿足客戶端的需要。後來想到了用一臺中轉伺服器,在這臺伺服器上架上websocket服務,然而移動端和pc端都是作為websocket的客戶端存在。

二、

       如過websocket要走wss通訊,就需要載入證書。載入證書之前首先的有證書,下面是一個做自簽證書的步驟:http://blog.csdn.net/langeldep/article/details/54846720

如果以上命令列還不能滿足你製作證書,你也可以用KeyStore Explorer  這個工具製作,很方便快捷。

 ExampleServer s = null;
                            InetSocketAddress address = new InetSocketAddress(ToolsUtils.getHostIPWIFI(SigninActivity.this), com.xgd.umsapp.mijia.util.Constant.port);
                               
                                     s = ExampleServer.getIstance(address, SigninActivity.this
); // ExampleServer s = new ExampleServer(address,SigninActivity.this); byte[] SwitchSoctketWss = tradeTlv.getTagValue(TradeTlv.SwitchSoctketWss); if (Arrays.equals(SwitchSoctketWss,"1".getBytes())) { LogUtilss.debugs
("","匯入wss證書"); s.setWebSocketFactory(loadBKS()); s.setConnectionLostTimeout(0); } String ssl = System.getProperty("SSL"); boolean b = System.getProperty("SSL")!= null; LogUtilss.debugs("","ssl ==="+ssl); LogUtilss.debugs("","boolean ==="+b); s.start();
  DefaultSSLWebSocketServerFactory loadBKS()
        {
            // load up the key store
String STORETYPE = "BKS";
           // String KEYSTORE = "climb2017.com.bks";
//            String KEYSTORE = "climb2017.com.jdk1.8.v1.bks";
String KEYSTORE = "xiaomi01.bks";
//            String KEYSTORE = "dms.xiaomi.com.bks";
//            String KEYPASSWORD = "ey6b1z17u1o34cg";
//            String STOREPASSWORD = "ey6b1z17u1o34cg";
String STOREPASSWORD = "12345678";
            String KEYPASSWORD = "12345678";

            SSLContext sslContext = null;
            KeyStore ks = null;
            try {
                ks = KeyStore.getInstance(STORETYPE);
                InputStream cerFileInputStrem = getCerFileInputStrem(KEYSTORE);
                ks.load(cerFileInputStrem, STOREPASSWORD.toCharArray());

                //KeyManagerFactory kmf = KeyManagerFactory.getInstance( "X509" );
KeyManagerFactory kmf = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm() );
                kmf.init( ks, KEYPASSWORD.toCharArray() );
               // kmf.init( ks, new char[0] );
               // TrustManagerFactory tmf = TrustManagerFactory.getInstance( "X509" );
TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm() );
                tmf.init( ks );

                //sslContext = SSLContext.getInstance( "TLS" );
sslContext = SSLContext.getInstance( "SSL" );
                sslContext.init( kmf.getKeyManagers(), tmf.getTrustManagers(), null );
                LogUtilss.debugs("","wss服務開啟");
            } catch (Exception e) {
                e.printStackTrace();
            }

            return  new DefaultSSLWebSocketServerFactory( sslContext );

        }