注:主要的问题是当浏览器窗口直接关闭时,后台会报异常,因为后台还在继续向浏览器端写数据,但是浏览器已经关闭了,会报java.net.SocketException:peer:Socket write error异常。所以当我们把窗口关闭的时候要通知后台不要再向浏览器端写数据了,
但是window.onclose(),经本人验证已经不起作用了(验证过程太尼玛恶心了),所以我采用另一种方法,使用body标签的onbeforeunload事件,这个事件是在页面刷新或者窗口关闭时触发,所以我在其触发函数中写入了 webSocket.close();来通知后台不要再向前段写数据了,然后webSocket连接就会自动断开,就不会有异常了。
前台:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
var webSocket=new WebSocket(‘ws://localhost:8080/JavaWeb/websocket‘);
webSocket.onerror = function(event) {
onError(event)
};
webSocket.onopen = function(event) {
onOpen(event)
};
webSocket.onmessage = function(event) {
onMessage(event)
};
function onMessage(event) {
document.getElementById(‘messages‘).innerHTML
+= ‘\n‘ + event.data;
}
function onOpen(event) {
document.getElementById(‘messages‘).innerHTML
= ‘Connection established‘;
}
function onError(event) {
alert(event.data);
}
function start() {
var content= document.getElementById(‘UserMessage‘).value;
//webSocket.send(‘hello‘);
webSocket.send(content);
return false;
}
/*
window.onclose()方法不管用,采用曲线救国的方法,
使用body标签的onbeforeunload事件,当整个页面刷新或把浏览器页面关闭的时候,通知后台断开websocket连接
*/
function fnUnloadHandler(){
webSocket.close();
}
</script>
</head>
<body onbeforeunload="fnUnloadHandler()">
<div>
<input id="UserMessage" type="text">
<input type="submit" onclick="start()" />
</div>
<textarea id="messages" rows="10" cols="20"></textarea>
</body>
</html>
后端:
package WebSocket;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/websocket")
public class demo1 {
@OnMessage
public void onMessage(String message,Session session) throws IOException, InterruptedException{
System.out.println("Receive: "+message);
//获取所有客户端的session,然后一旦接收到消息就为每一个客户端发送消息
Set sessions=session.getOpenSessions();
System.out.println(sessions.size());
Iterator it=sessions.iterator();
while(it.hasNext()){
Session s1=(Session) it.next();
s1.getBasicRemote().sendText(message);
}
}
@OnOpen
public void onOpen() {
System.out.println("Client connected");
}
@OnClose
public void onClose() {
System.out.println("Connection closed");
}
}