服务端 Java 代码:

final public class CounterSocketServlet extends WebSocketServlet {


    @Override

    protected WebSocket doWebSocketConnect(final HttpServletRequest hsr,

                                           final String string) {

        return new CounterSocket();

    }


    final class CounterSocket implements WebSocket {


        private Outbound outbound;


        public void onConnect(final Outbound outbound) {

            System.out.println("onConnect");

            this.outbound = outbound;

        }


        public void onMessage(final byte frame, final String data) {

            System.out.println("onMessage");


            if (data.equals("Hello, Server!")) {

                new Thread() {


                    @Override

                    public void run() {

                        try {

                            outbound.sendMessage(frame, "Hello, browser :-)");


                            int i = 0;

                            while (true) {

                                sleep(1000);

                                outbound.sendMessage(frame, String.valueOf(i++));

                            }


                        } catch (final Exception e) {

                            System.err.println(e.getMessage());

                        }

                    }

                }.start();

            }

        }


        public void onMessage(final byte frame, final byte[] data,

                              final int offset, final int length) {

            throw new UnsupportedOperationException("Not supported yet.");

        }


        public void onDisconnect() {

            System.out.println("onDisconnect");

        }

    }

}



浏览器客户端 HTML 代码:

<html>

    <head>

        <title>WebSoket Demo</title>

        <script type="text/javascript">

            if (!window.WebSocket) {

                alert("WebSocket not supported by this browser!");

            }

            

            function display() {

                var valueLabel = document.getElementById("valueLabel");

                valueLabel.innerHTML = "";

                var ws = new WebSocket(

                    "ws://localhost:8080/WebSocketDemo/counter-socket");

                ws.onmessage = function(evt) {

                    valueLabel.innerHTML = evt.data;

                };


                ws.onclose = function() {

                };


                ws.onopen = function() {

                    ws.send("Hello, Server!");

                };

            }

        </script>

    </head>

    <body onload="display();">

        <div id="valueLabel"></div>

    </body>

</html>