在html5中使用,目前主流的浏览器都基本已经支持ws协议,只需要在js中直接使用即可

    在html中:

    1. <!DOCTYPE HTML>
    2. <html>
    3. <head>
    4. <meta charset="utf-8">
    5. <meta name="apple-mobile-web-app-capable" content="yes"/>
    6. <meta name="apple-mobile-web-app-status-bar-style" content="black"/>
    7. <meta name="format-detection" content="telephone=no">
    8. <meta name="viewport" content="minimum-scale=1.0,maximum-scale=1,width=device-width,user-scalable=no"/>
    9. <title>WS测试</title>
    10. </head>
    11. <body>
    12. <section class="nav">
    13. <div class="subNav">
    14. <div class="slipMarquee" id="stock">
    15. </div>
    16. <div>
    17. <input type="text" id="txt"/>
    18. <button value="send" onclick="send();">send</button>
    19. </div>
    20. </div>
    21. </section>
    22. <script language="javascript" type="text/javascript">
    23. window.WebSocket = window.WebSocket || window.MozWebSocket;
    24. var socket = new WebSocket("ws://localhost:8888/echo");
    25. // 注意这里的ip地址改为你自己的地址,创建sockect客户端
    26. //如果是ssl,则需要把ws:// -> wss:// 如果是自签名证书,一般浏览器是不支持的
    27. socket.onopen = function () {
    28. socket.onclose = function (e) {// 关闭连接处理事件
    29. alert('close the socket');
    30. };
    31. socket.onerror = function (msg) {// 出错处理事件
    32. alert('error:' + msg);
    33. };
    34. };
    35. socket.onmessage = function (e) {
    36. // 收到消息处理事件,将收到的内容显示在页面上
    37. document.getElementById('stock').innerHTML = '<font color =red>' + event.data + '</font>';
    38. };
    39. function send() {// 发送输入
    40. socket.send(document.getElementById('txt').value);
    41. }
    42. </script>
    43. </body>
    44. </html>

    在java中:

    先导入一个java ws库的依赖

    <dependency>
                <groupId>org.java-websocket</groupId>
                <artifactId>Java-WebSocket</artifactId>
                <version>1.4.0</version>
            </dependency>
    

    示例:

    public class WsClient {
    
        static ThreadPool threadPool = new ThreadPool(ThreadPool.FixedThread, 10);
        private static String PROTOCOL = "TLSv1.2";
    
        public static void main(String[] args) throws Exception {
            //System.setProperty("javax.net.debug", "all");
            System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
            //开启ssl
            WebSocketClientInst chatclient = new WebSocketClientInst(new URI("wss://localhost:8888/echo"));
    
            //获取证书
            String pkPath = ResourceUtils.getURL("classpath:clientStore.jks").getPath();
            //ssl配置
            SslConfig sSLConfig = new SslConfig();
            sSLConfig.setKeyFile(pkPath);
            sSLConfig.setKeyPassword("123456");
            sSLConfig.setKeystorePassword("123456");
            sSLConfig.setTrustFile(pkPath);
            sSLConfig.setTrustPassword("123456");
            //设置客户端模式
            sSLConfig.setClientMode(true);
            SSLContext sslContext = init(sSLConfig);
            SSLSocketFactory factory = sslContext.getSocketFactory();
            //设置ssl
            chatclient.setSocketFactory(factory);
            //连接服务器
            chatclient.connectBlocking();
    
            boolean loop = true;
            int times = 0;
            while (loop) {
                times++;
                if (ReadyState.OPEN.equals(chatclient.getReadyState())) {
                    chatclient.send("123");  //发送
                    Thread.sleep(1000);
                } else {
                    System.out.println("还没ready, 继续进行中");
                    if (times <= 10) {
                        Thread.sleep(1000);
                    } else {
                        System.out.println("超时");
                        break;
                    }
                }
            }
        }
    
    
        /**
         * 初始化
         *
         * @param config
         */
        private static SSLContext init(SslConfig config) {
    
            SSLContext sslContext = null;
            try {
    
                KeyManager[] keyManagers = null;
                if (config.getKeyFile() != null) {
                    // 密钥库KeyStore
                    KeyStore ks = KeyStore.getInstance("JKS");
                    // 加载服务端的KeyStore,用于检查密钥库完整性的密码
                    ks.load(new FileInputStream(config.getKeyFile()), config.getKeystorePassword().toCharArray());
                    // 初始化密钥管理器
                    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
                    kmf.init(ks, config.getKeyPassword().toCharArray());
                    keyManagers = kmf.getKeyManagers();
                }
    
                //初始化签名证书管理器
                TrustManager[] trustManagers;
                if (config.getTrustFile() != null) {
                    // 密钥库KeyStore
                    KeyStore ts = KeyStore.getInstance("JKS");
                    // 加载信任库
                    ts.load(new FileInputStream(config.getTrustFile()), config.getTrustPassword().toCharArray());
                    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
                    tmf.init(ts);
                    trustManagers = tmf.getTrustManagers();
                } else {
                    trustManagers = new TrustManager[]{new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                        }
    
                        @Override
                        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                        }
    
                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }
                    }};
                }
    
                //初始化上下文
                sslContext = SSLContext.getInstance(PROTOCOL);
                sslContext.init(keyManagers, trustManagers, new SecureRandom());
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return sslContext;
        }
    
    }
    
    
    //ws客户端
    class WebSocketClientInst extends WebSocketClient {
    
        public WebSocketClientInst(URI serverUri) {
            super(serverUri);
        }
    
        @Override
        public void onOpen(ServerHandshake handshakedata) {
            System.out.println("Connected");
    
        }
    
        @Override
        public void onMessage(String message) {
            System.out.println("got: " + message);
    
        }
    
        @Override
        public void onClose(int code, String reason, boolean remote) {
            System.out.println("Disconnected");
    
        }
    
        @Override
        public void onError(Exception ex) {
            ex.printStackTrace();
    
        }
    
    }