html5 websockt 示例

来源:互联网 发布:em算法 统计学方法 编辑:程序博客网 时间:2024/06/06 15:27


示例演示:你每次输入hello 然后点【发送】,页面上的数字就+1
结果如图:



代码如下:

<html>
    <head>
        <title>WebSoket Demo</title>
        <script type="text/javascript">
        //浏览器不支持 websocket
       
            if (!window.WebSocket) {
                alert("WebSocket not supported by this browser!");
            }
            var wsutil = {
                    join: function() {
                      this._ws=new WebSocket("ws://localhost:8080/ws/counter/");
                      this._ws.onopen=this._onopen;
                      this._ws.onmessage=this._onmessage;
                      this._ws.onclose=this._onclose;
                    },
                    _onopen: function(text){
                        wsutil._send(text);
                      },
                      _send: function(message){
                        if (this._ws)
                          this._ws.send(message);
                      },
                      _onmessage: function(m) {
                      var valueLabel = document.getElementById("valuetime");
                      valueLabel.innerHTML = m.data; },
                      _onclose: function(m) {}
           
        };
           
           
            function sendmethod(){
            wsutil._onopen("hello")
            }
        </script>
    </head>
    <body onload="wsutil.join()">
        发送hello的次数:<div id="valuetime"></div>
       
        </br>
        <input type="text" id="msg" value="" />
        <input type="button" value="发送" id="send" onclick="sendmethod()"/>
    </body>
</html>

后台java代码:
public static Long i=0l;

@Override
      public void onMessage(String data) {
System.out.println(data);
           if ("hello".equals(data)) {
            try {
            i=i+1;
con.sendMessage(i.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
            }
}
原创粉丝点击