示例示範:你每次輸入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 ο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();
}
}
}
-
- 大小: 1.6 KB
-
- 大小: 1.7 KB
- 檢視圖檔附件