html5 websockt 示例

[img]http://dl.iteye.com/upload/attachment/0074/0715/da2ea844-03d3-382f-8ec5-adc4471a6786.png[/img]
示例演示:你每次输入hello 然后点【发送】,页面上的数字就+1
结果如图:

[img]http://dl.iteye.com/upload/attachment/0074/0717/e8f740b5-c846-383f-884b-25365e0f1571.png[/img]

代码如下:

<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 οnlοad="wsutil.join()">
发送hello的次数:<div id="valuetime"></div>

</br>
<input type="text" id="msg" value="" />
<input type="button" value="发送" id="send" οnclick="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();
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值