//pom
<!-- webSocket 开始-->
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- webSocket 结束-->
/******************************ManagerWebsocket.java********************************/
package com.common.utils;
import javax.servlet.http.HttpServlet;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
//该注解用来指定一个URI,客户端可以通过这个URI来连接到WebSocket,类似Servlet的注解mapping;
@ServerEndpoint(value = "/websocket")
public class ManagerWebsocket extends HttpServlet {
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static CopyOnWriteArraySet<ManagerWebsocket> webSocketSet = new CopyOnWriteArraySet<ManagerWebsocket>();
//这个session不是Httpsession,相当于用户的唯一标识,用它进行与指定用户通讯
private javax.websocket.Session session=null;
/**
* @OnOpen allows us to intercept the creation of a new session.
* The session class allows us to send data to the user.
* In the method onOpen, we'll let the user know that the handshake was
* successful.
* 建立websocket连接时调用
*/
@OnOpen
public void onOpen(Session session){
System.out.println("Session " + session.getId() + " has opened a connection");
try {
this.session=session;
webSocketSet.add(this); //加入set中
session.getBasicRemote().sendText("Connection Established");
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* When a user sends a message to the server, this method will intercept the message
* and allow us to react to it. For now the message is read as a String.
* 接收到客户端消息时使用,这个例子里没用
*/
@OnMessage
public void onMessage(String message, Session session){
System.out.println("Message from " + session.getId() + ": " + message);
}
/**
* The user closes the connection.
*
* Note: you can't send messages to the client from this method
* 关闭连接时调用
*/
@OnClose
public void onClose(Session session){
webSocketSet.remove(this); //从set中删除
System.out.println("Session " +session.getId()+" has closed!");
}
/**
* 注意: OnError() 只能出现一次. 其中的参数都是可选的。
* @param session
* @param t
*/
@OnError
public void onError(Session session, Throwable t) {
t.printStackTrace();
}
/**
* 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
* @throws IOException
* 发送自定义信号,“1”表示告诉前台,数据库发生改变了,需要刷新
*/
public static void sendMessage() throws IOException{
//群发消息
for(ManagerWebsocket item: webSocketSet){
try {
item.session.getBasicRemote().sendText("1");
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
}
/***********************************js*************************************/
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
//建立连接,这里的/websocket ,是ManagerServlet中开头注解中的那个值
var pathName=window.document.location.pathname;
var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
websocket = new WebSocket("ws://localhost:"+window.location.port+projectName+"/websocket");
}
else {
alert('当前浏览器 Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
if(event.data=="1"){
//此处刷新
alert("success")
}
}
//连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
console.info(innerHTML)
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}