开发者社区> 问答> 正文

Tomcat7中实现WebSocket 使用HttpSession,如何配置?

Tomcat7中实现WebSocket 中 Endpoint的Session跟httpSession不是同一个东西,如何在WebSocket中访问HttpSocket呢?
这样可以获取HttpSocket中的对象,例如getAttribute()

展开
收起
落地花开啦 2016-05-31 13:52:24 6251 0
1 条回答
写回答
取消 提交回答
  • 喜欢技术,喜欢努力的人

    首先要继承 ServerEndpointConfig,并实现 modifyHandshake方法,该方法有个
    HandshakeRequest参数,代码如下:

    import javax.servlet.http.HttpSession;
    import javax.websocket.HandshakeResponse;
    import javax.websocket.server.HandshakeRequest;
    import javax.websocket.server.ServerEndpointConfig;
     
    public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator
    {
        @Override
        public void modifyHandshake(ServerEndpointConfig config, 
                                    HandshakeRequest request, 
                                    HandshakeResponse response)
        {
            HttpSession httpSession = (HttpSession)request.getHttpSession();
            config.getUserProperties().put(HttpSession.class.getName(),httpSession);
        }
    }

    这时可以在实现ServerEndPoint的类中作为configurator参数

    package action;
     
    import java.io.IOException;
    import java.util.Set;
    import java.util.concurrent.CopyOnWriteArraySet;
     
    import javax.servlet.http.HttpSession;
    import javax.websocket.EndpointConfig;
    import javax.websocket.OnClose;
    import javax.websocket.OnError;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.Session;
    import javax.websocket.server.ServerEndpoint;
    import org.apache.log4j.Logger;
     
    import common.GetHttpSessionConfigurator;
    import common.HTMLFilter;
     
    @ServerEndpoint(value = "/action/websocket/chat",configurator=GetHttpSessionConfigurator.class)
    public class ChatAction{
    private final static Logger log = Logger.getLogger(ChatAction.class);
        private static final Set<ChatAction> onlineUsers =
                new CopyOnWriteArraySet<ChatAction>();
        private String nickname;
        private Session session;
        private HttpSession httpSession;
       
        @OnOpen
        public void start(Session session, EndpointConfig config) {
            this.session = session;
            this.httpSession = (HttpSession) config.getUserProperties()
                    .get(HttpSession.class.getName());
            this.nickname=(String) httpSession.getAttribute("loginOperatorId");
            onlineUsers.add(this);
            String message = String.format("* %s %s", nickname, " from websocket 上线了...");
            broadcast(message);
        }
     
        @OnClose
        public void end(Session session) {
            onlineUsers.remove(this);
            String message = String.format("* %s %s",
                    nickname, " from websocket 已经离开...");
            broadcast(message);
        }
     
        @OnMessage
        public void incoming(String message, EndpointConfig config) {
            // Never trust the client
            String filteredMessage = String.format("%s: %s",
                    nickname, HTMLFilter.filter(message.toString()));
            broadcast(filteredMessage);
        }
     
        @OnError
        public void onError(Throwable t) throws Throwable {
            log.error("错误: " + t.toString(), t);
        }
     
        private static void broadcast(String msg) {
            for (ChatAction client : onlineUsers) {
                try {
                    synchronized (client) {
                        client.session.getBasicRemote().sendText(msg);
                    }
                } catch (IOException e) {
                    log.debug("错误: 消息发送失败!", e);
                    onlineUsers.remove(client);
                    try {
                        client.session.close();
                    } catch (IOException e1) {
                        // Ignore
                    }
                    String message = String.format("* %s %s",
                            client.nickname, " from websocket 已经离开...");
                    broadcast(message);
                }
            }
        }
    }
    2019-07-17 19:21:50
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Apache Tomcat 的云原生演进 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载