基于tomcat8实现websocket服务

/**
 * tomcat8 websocket
 * Created by aiyaoxin on 2018/1/23 15:44
 */
@ServerEndpoint(value = "/websocket", configurator = HttpSessionConfigurator.class)
public class MyWebSocket {

    private static final Logger logger = LoggerFactory.getLogger(MyWebSocket.class);

    private static final String CLIENT = "client_";

    private static final Map<String, Set<MyWebSocket>> connections = new ConcurrentHashMap<>();// 全部websocket链接

    private Set<MyWebSocket> sessionConnections;// 当前会话所有socket链接

    private Session session;// websocket会话

    private String nickname;// 客户端昵称

    private String sessionId;// http会话标识

    private HttpSession httpSession;// http会话

    @OnOpen
    public void start(Session session, EndpointConfig config) {
        this.session = session;
        this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        String sessionId = (String) config.getUserProperties().get(Constant.SESSIONID);
        this.sessionId = sessionId;
        Set<MyWebSocket> sessionConnections = connections.get(sessionId);
        if (sessionConnections == null) {
            sessionConnections = new CopyOnWriteArraySet<>();
            connections.put(sessionId, sessionConnections);
        }
        this.sessionConnections = sessionConnections;
        sessionConnections.add(this);
        nickname = CLIENT + sessionConnections.size();
        String message = String.format("==%s %s==", nickname, "has joined");
        broadcast(message);
    }

    @OnClose
    public void end(Session session) {
        sessionConnections.remove(this);
        if (sessionConnections.size() == 0) {
            connections.remove(this.sessionId);
        }
        String message = String.format("==%s %s==", nickname, "has disconnected");
        broadcast(message);
    }

    @OnMessage
    public void incoming(Session session, String message) {
        broadcast(message);
    }

    @OnError
    public void onError(Throwable t) throws Throwable {
        logger.error("MyWebSocket Error: " + t.toString());
    }

    public static void send(String sessionId, String msg) {
        Set<MyWebSocket> sessionConnections = connections.get(sessionId);
        for (MyWebSocket client : sessionConnections) {
            send(client, msg);
        }
    }

    public static void broadcast(String msg) {
        for (Map.Entry<String, Set<MyWebSocket>> entry : connections.entrySet()) {
            Set<MyWebSocket> sessionConnections = entry.getValue();
            for (MyWebSocket client : sessionConnections) {
                send(client, msg);
            }
        }
    }

    private static void send(MyWebSocket client, String msg) {
        try {
            synchronized (client) {
                client.session.getBasicRemote().sendText(msg);
            }
        } catch (IOException e) {
            logger.error("MyWebSocket Error: Failed to send message to client", e);
            client.sessionConnections.remove(client);
            if (client.sessionConnections.size() == 0) {
                connections.remove(client.sessionId);
            }
            IOUtils.closeQuietly(client.session);
            String message = String.format("==%s %s==", client.nickname, "has been disconnected");
            broadcast(message);
        }
    }

}
/**
 * 提取会话标识
 * Created by aiyaoxin on 2018/1/31 11:08
 */
public class HttpSessionConfigurator extends ServerEndpointConfig.Configurator {
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        HttpSession session = (HttpSession) request.getHttpSession();
        sec.getUserProperties().put(HttpSession.class.getName(), session);
        sec.getUserProperties().put(Constant.SESSIONID, session.getId());
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值