1、开发环境eclipse、tomcat7、jdk1.7
2、pom jar包引用
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
3、服务端
@ServerEndpoint(value = "/websocket", configurator = GetHttpSessionConfigurator.class)
public class SessionStatusWebSocket {
private static int onlineCount = 0;
// concurrent包的线程安全Set,用来存放每个客户端对应的webSocketSet对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static CopyOnWriteArraySet<SessionStatusWebSocket> webSocketSet = new CopyOnWriteArraySet<SessionStatusWebSocket>();
// 一个会话可能造成
private static Map<String, HttpSession> socketNumb = new ConcurrentHashMap<String, HttpSession>();
// 与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
// 整个会话
private HttpSession httpSession;
/**
* 连接建立成功调用的方法
*
* @param session
* 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
this.session = session;
this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
webSocketSet.add(this); // 加入set中
addOnlineCount(); // 连接数+1
System.out.println("有新连接加入!当前连接数为:" + getOnlineCount());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); // 从set中删除
subOnlineCount(); // 在线数减1
System.out.println("有一连接关闭!当前连接数为:" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message
* 客户端发送过来的消息
* @param session
* 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
try {
sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
// 查询用户是否过期
String sessionToken = (String) httpSession.getAttribute("sid");
if (sessionToken != null) {
Integer userId = UmDBManager.webSocketCheckUserSessionToken(sessionToken);
if (userId == null) {
message = "0";// 用户正常退出
} else if (userId == 0) {
message = "1";// 该用户在其他地方登入
}
} else {
message = "2";// 服务器重启httpsession更改,但是客户端sid还在
}
this.session.getBasicRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
onlineCount = SessionStatusWebSocket.getOnlineCount();
onlineCount++;
}
public static synchronized void subOnlineCount() {
onlineCount = SessionStatusWebSocket.getOnlineCount();
onlineCount--;
}
}
4、GetHttpSessionConfigurator配置类获取httpsession
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;
public class GetHttpSessionConfigurator extends Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
HttpSession httpSession = (HttpSession) request.getHttpSession();
sec.getUserProperties().put(HttpSession.class.getName(), httpSession);
}
}
5、此时httpsession为null,需要配置拦截器在容器初始化时获取httpsession
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
public class RequestListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
}
public RequestListener() {
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
// 将所有request请求都携带上httpSession
((HttpServletRequest) sre.getServletRequest()).getSession();
}
}
6、web监听器配置
<!--HttpSessionListener 监听器-->
<listener>
<listener-class>包路径.RequestListener</listener-class>
</listener>
7、前端连接测试
//读取配置文件获取webSocketurl
var wswebsocketUrl = data.webSocketUrl;
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
console.log(wswebsocketUrl);
websocket = new WebSocket("ws://" + wswebsocketUrl);
}
else {
alert('当前浏览器 Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
var msg = event.data;
//业务处理逻辑
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket连接关闭");
window.clearInterval(timer);
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
// console.log(innerHTML);
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
//var sid = $.cookie('sid'); //后台将httpOnly设置为false
websocket.send("登入状态");
}
var timer = setInterval(send, 1000);