package com.shlanbao.tzsc.pms.websocket;
|
|
import org.apache.commons.collections.MapUtils;
|
import org.springframework.web.socket.CloseStatus;
|
import org.springframework.web.socket.TextMessage;
|
import org.springframework.web.socket.WebSocketSession;
|
import org.springframework.web.socket.handler.TextWebSocketHandler;
|
|
/**
|
|
*/
|
public class MyWebSocketHandler extends TextWebSocketHandler {
|
@Override
|
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
|
super.afterConnectionEstablished(session);
|
String userId = MapUtils.getString(session.getAttributes(),"name");
|
System.out.println("websocket连接:用户-" +userId);
|
//记录连接的session
|
if(userId!=null)
|
WebSocketSessionUtils.getInstance().add(userId,session);
|
|
}
|
@Override
|
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
|
super.handleTextMessage(session, message);
|
String userId = MapUtils.getString(session.getAttributes(),"name");
|
//回复消息
|
// TextMessage returnMessage = new TextMessage("Hi:"+userId+"..your message:"+message.getPayload()+" I have received,now I tell you");
|
// WebSocketSessionUtils.getInstance().sendMessageToTarget(userId,returnMessage);
|
|
}
|
|
@Override
|
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
|
super.handleTransportError(session, exception);
|
String userId = MapUtils.getString(session.getAttributes(),"name");
|
System.out.println("websocket错误:用户-" +userId+"/错误-"+exception.toString());
|
WebSocketSessionUtils.getInstance().remove(userId);
|
}
|
|
@Override
|
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
|
super.afterConnectionClosed(session, status);
|
|
String userId = MapUtils.getString(session.getAttributes(),"name");
|
System.out.println("websocket断开:用户-" +userId);
|
WebSocketSessionUtils.getInstance().remove(userId);
|
}
|
}
|