一個基於webSocket實現前後端通訊的小demo
#sell
一般的web專案都是前臺向後臺傳送訊息,但是有些時候我們也需要從後端向前臺傳送訊息,比如說zfb的回撥資訊,微信的模板推送訊息等,下面通過Eclipse+Tomcat實現一個前後臺通訊的小demo;
先建立一個web專案 index.jsp寫一個簡單的頁面來顯示訊息
```
<%@ page language="java" pageEncoding="UTF-8" %>
<html>
<head>
<title>Java後端WebSocket的Tomcat實現</title>
</head>
<body>
Welcome
<br />
<input id="text" type="text" />
<button onclick="send()">傳送訊息</button>
<hr />
<button onclick="closeWebSocket()">關閉WebSocket連線</button>
<hr />
<div id="message"></div>
<script>
var websocket = null;
if('WebSocket' in window){
websocket = new WebSocket("ws://127.0.0.1:8080/testWebSocket/websocket")
}else{
alert("當前瀏覽器不支援websocket")
}
websocket.onerror = function(){
setMessageInHtml("傳送錯誤");
}
websocket.onopen = function(){
setMessageInHtml("建立連線")
}
websocket.onmessage = function(event){
setMessageInHtml(event.data);
}
websocket.onclose = function(){
setMessageInHtml("關閉WebSocket連線")
}
window.onbeforeunload = function(){
closeWebsocket();
}
function setMessageInHtml(message){
document.getElementById('message').innerHTML += message+'</br>'
}
function closeWebsocket(){
websocket.colse();
}
function send(){
var msg = document.getElementById('text').value;
websocket.send(msg);
}
</script>
</body>
</html>