精华内容
下载资源
问答
  • 获取Websocket会话

    2018-03-11 15:39:40
    <p>When connection from client-side (browser) is requested, server generates random <strong>token</strong> on websocket upgrade request and sends it via HTTP Set-Cookie header. Then, client ...
  • 前言 一般我们web网站都会有cookie来保存session ID,将用户和服务器保持在一次会话中,但是很遗憾,微信小程序不支持cookie,他的...如果要让小程序保持session一直,所以每次请求的时候wx.request header 加上coo...

    前言

    一般我们web网站都会有cookie来保存session ID,将用户和服务器保持在一次会话中,但是很遗憾,微信小程序不支持cookie,他的每一次请求就是一次会话,这样就会产生一个问题,每次请求都需要确定当前的用户是谁,但是我们又不能在每次请求的数据中携带用户的信息,这样是不安全的。
    如果要让小程序保持session一直,所以每次请求的时候wx.request   header 加上cookie,
    保持session 一致是否非常关键的,对取session 中的值非常重要,不然每次取到的都是空值
    我是在app.js 中的onLaunch 中向服务器请求获取sessionId.
    

    服务端不单单可以给小程序用,网页端(网页端也有很多坑,比如跨域的时候ajax不传一个重要参数 叫啥凭证值一定要为true,那么是获取不到握手前的session的,同理也是为了保持session一致,如果你遇到了问题,请联系我)也可以,我还有websocket 智能心跳,保证连接一直存活,有需要联系我,下方有邮件地址。

    好吧,来介绍一下我的websocket 的实现思路:
    1.要使用websocket 首先使用需要请求登录 下面是我的登录方法,每次请求把能能够标识这个小程序用户的唯一标识传过来,这个对之后单独给这个用户发送消息很重要。然后放入session中。

    @RequestMapping("login")
        public ReturnValue login(HttpServletRequest request, HttpSession session) throws Exception {
        	logger.info("登录websokcet.....sessionId:"+session.getId());
            String userId = request.getParameter("userId");
            String clientType=request.getParameter("clientType");
            if(Strings.isBlank(userId)||Strings.isBlank(clientType)) {
            	return new ReturnValue(false,"参数异常");
            }
            if(null!=session) {
            	logger.info("登陆WebSocket成功:"+("1".equals(clientType)?"P"+userId:"U"+userId));
                session.setAttribute("WEBSOCKET_SESSSION_ID", "1".equals(clientType)?"P"+userId:"U"+userId); //一般直接保存user实体
            }else {
            	logger.info("登陆WebSocket失败,session==null:"+("1".equals(clientType)?"P"+userId:"U"+userId));
            	logger.info("登录websocket+login时,获取session失败");
            }
            return new ReturnValue(true);
        }
    

    2.websocket 是基于tcp 3次握手的,所以我使用的是springboot 一个握手前的拦截器,来吧1中放入session中的唯一标识,放到websocket 会话中。就是下面的session获取不到,得不到其中的参数,为什么呢?握手前获取到session,如果小程序不传sessionId,也会获取不到session的,所以在小程序连接websocket时,也要传sessionId.

    app.globalData.webSocket=wx.connectSocket({
          url: "" + socketUrl + "/ptt/websocket/socketServer",
          header: {
            'Cookie': 'JSESSIONID=' + wx.getStorageSync("SessionId")
          },
          success() {
            console.log('连接成功');
            that.init();
          }
        });
    
    package com.zzd.ptt.comm.websocket;
    
    import java.util.Map;
    
    import javax.servlet.http.HttpSession;
    
    import org.apache.log4j.Logger;
    import org.springframework.http.server.ServerHttpRequest;
    import org.springframework.http.server.ServerHttpResponse;
    import org.springframework.http.server.ServletServerHttpRequest;
    import org.springframework.web.socket.WebSocketHandler;
    import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
    
    public class SpringWebSocketHandlerInterceptor extends HttpSessionHandshakeInterceptor {
        private static Logger logger = Logger.getLogger(SpringWebSocketHandler.class);
    
        @Override
        public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                       Map<String, Object> attributes) throws Exception {
        	logger.info("Before Handshake");
            if (request instanceof ServletServerHttpRequest) {
                ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
                HttpSession session = servletRequest.getServletRequest().getSession(false);
                HttpSession session2 = servletRequest.getServletRequest().getSession();
                logger.info("握手时,获取到的session:"+(session==null?session:session.getAttributeNames()));
                logger.info("握手时,获取到的session2:"+(session2==null?session2:session2.getId()));
                if (session != null) {
                    //使用拼接ID区分WebSocketHandler,以便定向发送消息
                    String sessionId = (String) session.getAttribute("WEBSOCKET_SESSSION_ID");  //一般直接保存user实体
                    if (sessionId!=null) {
                        attributes.put("WEBSOCKET_SESSSION_ID",sessionId);
                    }
    
                    //使用拼接ID区分WebSocketHandler,以便定向发送消息  出来处理工单也,在主页面的socket
                    String sessionNo_workOrderId = (String) session.getAttribute("WEBSOCKET_NO_WORKORDER_WAIT_MESSAGE_SESSSION_ID");  //一般直接保存user实体
                    if (sessionNo_workOrderId!=null) {
                        attributes.put("WEBSOCKET_NO_WORKORDER_WAIT_MESSAGE_SESSSION_ID",sessionNo_workOrderId);
                    }
                }
            }
            return super.beforeHandshake(request, response, wsHandler, attributes);
    
        }
    
        @Override
        public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Exception ex) {
            super.afterHandshake(request, response, wsHandler, ex);
        }
        
    }
    //
    

    3.编写websocket 处理类了 这个我是继承了 spring的websocket 的工具类

    package com.zzd.ptt.comm.websocket;
    
    import java.io.IOException;
    import java.util.Map;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.stream.Collector;
    import java.util.stream.Collectors;
    
    import org.apache.log4j.Logger;
    import org.apache.logging.log4j.util.Strings;
    import org.springframework.stereotype.Component;
    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;
    
    
    @Component
    public class SpringWebSocketHandler extends TextWebSocketHandler {
        
        private static Logger logger = Logger.getLogger(SpringWebSocketHandler.class);
    
        private static final Map<String, WebSocketSession> users;  //Map来存储WebSocketSession,key用USER_ID 即在线用户列表
     
        //用户标识
        private static final String USER_ID = "WEBSOCKET_SESSSION_ID";   //对应监听器从的key
     
        //没有工单的用户标识 等待消息时
        private static final String No_WORKORDER_USERID="WEBSOCKET_NO_WORKORDER_WAIT_MESSAGE_SESSSION_ID";
        static {
            users =  new ConcurrentHashMap<String, WebSocketSession>();
        }
     
        public SpringWebSocketHandler() {}
     
        /**
         * 连接成功时候,会触发页面上onopen方法
         */
        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws Exception {
     
        	logger.info("成功建立websocket连接!");
            String userId = (String) session.getAttributes().get(USER_ID);
            String no_workOrderId_userId = (String) session.getAttributes().get(No_WORKORDER_USERID);
            logger.info("成功建立websocket连接 userId=!"+userId);
            logger.info("成功建立websocket连接no_workOrderId_userId=!"+no_workOrderId_userId);
            if(Strings.isNotBlank(userId)) {
    //        	if(users.containsKey(userId)) {//如果已包含将关闭之前的session,发送消息到新的session
    //        		WebSocketSession wss=users.get(userId);
    //        		wss.close();
    //        	}
                users.put(userId,session);
            }
            if(Strings.isNotBlank(no_workOrderId_userId)) {
    //        	if(users.containsKey(no_workOrderId_userId)) {//如果已包含将关闭之前的session,发送消息到新的session
    //        		WebSocketSession wss=users.get(no_workOrderId_userId);
    //        		wss.close();
    //        	}
                users.put(no_workOrderId_userId,session);
            }
            logger.info("当前线上用户数量:"+users.size());
            logger.info(users.entrySet().stream().collect(Collectors.toList()));
        	logger.info(".......以上为用户session数量");
            //这块会实现自己业务,比如,当用户登录后,会把离线消息推送给用户
            //TextMessage returnMessage = new TextMessage("成功建立socket连接,你将收到的离线");
            //session.sendMessage(returnMessage);
        }
     
        /**
         * 关闭连接时触发
         */
        @Override
        public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
            String userId= (String) session.getAttributes().get(USER_ID);
            logger.info("用户"+userId+"已退出!");
            if(Strings.isNotBlank(userId)) {
               users.remove(userId);
            }
            logger.info("剩余在线用户"+users.size());
        }
     
        /**
         * js调用websocket.send时候,会调用该方法
         */
        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
     
            super.handleTextMessage(session, message);
            logger.info("websocket session:"+session.getAttributes().entrySet().stream().collect(Collectors.toList()));
            sendMessageToUser(session.getId(),message);
    //        session.getAttributes()
            /**
             * 收到消息,自定义处理机制,实现业务
             */
            logger.info("服务器收到消息:"+message);
     
            if(message.getPayload().startsWith("#anyone#")){ //单发某人
     
                 sendMessageToUser((String)session.getAttributes().get(USER_ID), new TextMessage("服务器单发:" +message.getPayload())) ;
     
            }else if(message.getPayload().startsWith("#everyone#")){
     
                 sendMessageToUsers(new TextMessage("服务器群发:" +message.getPayload()));
     
            }else{
     
            }
     
        }
     
        @Override
        public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
            if(session.isOpen()){
                session.close();
            }
            logger.info("传输出现异常,关闭websocket连接... ");
            String userId= (String) session.getAttributes().get(USER_ID);
            users.remove(userId);
        }
     
        public boolean supportsPartialMessages() {
     
            return false;
        }
     
     
        /**
         * 给某个用户发送消息
         *
         * @param userId
         * @param message
         */
        public void sendMessageToUser(String userId, TextMessage message) {
        	logger.info("开始发送消息!给->"+userId +"   信息"+message);
            for (String id : users.keySet()) {
            	logger.info("目前有:键值"+id+"  会话"+users.get(id));
                if (id.equals(userId)) {
                    try {
                        if (users.get(id).isOpen()) {
                            users.get(id).sendMessage(message);
                            logger.info("成功发送消息给:"+userId);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
     
        /**
         * 给所有在线用户发送消息
         *
         * @param message
         */
        public void sendMessageToUsers(TextMessage message) {
            for (String userId : users.keySet()) {
                try {
                    if (users.get(userId).isOpen()) {
                        users.get(userId).sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        //判断用户是否在线
        public boolean checkUserInline(String uorpId) {
        	if(users.containsKey(uorpId)) {
        		WebSocketSession wss=users.get(uorpId);
        		return wss!=null&&wss.isOpen();
        	}
        	return false;
        }
    }
    //
    

    4.编写发送消息的方法 ,为什么要单独写一个发送消息的方法呢?因为在处理类中使用autowired 不能够实例化bean,这个没有去仔细看为什么不能?下面是我写的handler发送方法。上面可以放很多bean

     @Bean//这个注解会从Spring容器拿出Bean
        public SpringWebSocketHandler infoHandler() {
     
            return new SpringWebSocketHandler();
        }
     @RequestMapping("send")
        public ReturnValue send(HttpServletRequest request,HttpSession session) {
        	String userId = request.getParameter("userId");
            String proxyId=request.getParameter("proxyId");
            String workOrderId=request.getParameter("workOrderId");
            String clientType=request.getParameter("clientType");
            String message=request.getParameter("message");
            WorkOrderLeavMsg workOrderLeaeMsg=new WorkOrderLeavMsg();
            workOrderLeaeMsg.setContent(message);
            workOrderLeaeMsg.setWorkOrderId(Integer.parseInt(workOrderId));
            if("1".equals(clientType)) {
            	workOrderLeaeMsg.setProxyId(Integer.parseInt(proxyId));
            }else if("0".equals(clientType)) {
            	workOrderLeaeMsg.setUserId(Integer.parseInt(userId));
            }
            String lastId="1".equals(clientType)?"U"+userId:"P"+proxyId;
            SpringWebSocketHandler wshandler=infoHandler();
            EnumCode enumCode=new EnumCode();
            enumCode.setCode("0");//未读
            workOrderLeaeMsg.setLeaveMsgType(enumCode);
            //入库
            if(wos.addWorkOrderLeavMsg(workOrderLeaeMsg)) {
              //给还在处理页面的用户发送消息
            	wshandler.sendMessageToUser(lastId,new TextMessage("A+"+"**"+workOrderId+"**"+message));
            }
            //修改工单状态为待反馈
            WorkOrder wo=new WorkOrder();
            wo.setId(Integer.parseInt(workOrderId));
            Product p=new Product();
            p.setId("1".equals(clientType)?Long.parseLong(proxyId):Long.parseLong(userId));
            wo.setProduct(p);
            wo.setState("2");
            wos.updateWorkOrder(wo);
            return new ReturnValue(true);
        }
    

    按照这几部绝对可以行的通,我走了太多的弯路,所以才写下这篇,希望能帮到其他人,如果按照我的步骤还不行,请联系我 给我发邮件有空一定回1608379481@qq.com,码字不易给个好评咯。

    展开全文
  • websocket获取httpsession

    千次阅读 2019-03-06 10:44:52
    1.新建 public class HttpSessionConfigurator extends Configurator { ... public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { ...

    1.新建

    public class HttpSessionConfigurator extends Configurator {
    
        @Override
        public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
            HttpSession httpSession = (HttpSession) request.getHttpSession();
            sec.getUserProperties().put(HttpSession.class.getName(), httpSession);
        }
    
    }

    2.新建

    @Component
    public class RequestListener implements ServletRequestListener {
    
        public void requestInitialized(ServletRequestEvent sre)  {
            //将所有request请求都携带上httpSession
            ((HttpServletRequest) sre.getServletRequest()).getSession();
    
        }
        public RequestListener() {
        }
    
        public void requestDestroyed(ServletRequestEvent arg0)  {
        }
    }

    3.在配置类中添加

    @Autowired
    private RequestListener requestListener;
    
    @Bean
    public ServletListenerRegistrationBean<RequestListener> servletListenerRegistrationBean() {
        ServletListenerRegistrationBean<RequestListener> servletListenerRegistrationBean = new ServletListenerRegistrationBean<>();
        servletListenerRegistrationBean.setListener(requestListener);
        return servletListenerRegistrationBean;
    }

    4.在@ServerEndpoint后面添加配置类

    @ServerEndpoint(value="/ws",configurator = HttpSessionConfigurator.class)

    并修改onOpen方法

    public void onOpen(Session session,EndpointConfig config) {
        HttpSession httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        ……………………
    }
    

    注意:我自己写的时候发现httpsession总是没有值,后来发现原因在于自己浏览器访问的ip用的127.0.0.1而websocket连接用的ip为电脑实际ip,改成一样的就好了。感谢网友分享让我找到原因https://blog.csdn.net/qq_35101027/article/details/80745664。另外,其他部分代码是根据https://www.cnblogs.com/zhuxiaojie/p/6238826.html学着写的,原文更加详细,大家可以看看,同样表示感谢。

    展开全文
  • and <code>websocket.Conn</code> has a <code>Request</code> method returning *http.Request</code>. <p>My idea is to subscribe the user to different channels depending on the subdomain they use to ...
  • 后台中ServerHttpRequest request中的session是空的,前端通过wx.connectSocket传递的data也没看到。2.可以从前端网后台传递信息,但是后台往前端发送时会报出如下错误有没有大神能告知下解决方案呢?Java后台实现...

    在使用java作为后台测试微信小程序时,发现:

    1.后台中ServerHttpRequest request中的session是空的,前端通过wx.connectSocket传递的data也没看到。

    2.可以从前端网后台传递信息,但是后台往前端发送时会报出如下错误

    有没有大神能告知下解决方案呢?

    Java后台实现WebSocket时一共尝试了两种方案,一种是java+spring,一种是纯spring的,而且两者都会出现上面的情况,同时

    其中:

    springMVC时报如下错误:

    Exception in thread "Thread-21" java.lang.IllegalStateException: The remote endpoint was in state [STREAM_WRITING] which is an invalid state for called method

    at org.apache.tomcat.websocket.WsRemoteEndpointImplBase$StateMachine.checkState(WsRemoteEndpointImplBase.java:1225)

    at org.apache.tomcat.websocket.WsRemoteEndpointImplBase$StateMachine.textPartialStart(WsRemoteEndpointImplBase.java:1182)

    at org.apache.tomcat.websocket.WsRemoteEndpointImplBase.sendPartialString(WsRemoteEndpointImplBase.java:222)

    at org.apache.tomcat.websocket.WsRemoteEndpointBasic.sendText(WsRemoteEndpointBasic.java:49)

    at org.springframework.web.socket.adapter.standard.StandardWebSocketSession.sendTextMessage(StandardWebSocketSession.java:197)

    at org.springframework.web.socket.adapter.AbstractWebSocketSession.sendMessage(AbstractWebSocketSession.java:104)

    at cn.zhonya.WXTalkDome.webSocket.MyWebSocketHandler$1.run(MyWebSocketHandler.java:139)

    at java.lang.Thread.run(Thread.java:745)

    java+spring时会报如下错误:

    java.lang.IllegalStateException: The remote endpoint was in state [WRITER_WRITING] which is an invalid state for called method

    at org.apache.tomcat.websocket.WsRemoteEndpointImplBase$StateMachine.checkState(WsRemoteEndpointImplBase.java:1225)

    at org.apache.tomcat.websocket.WsRemoteEndpointImplBase$StateMachine.textStart(WsRemoteEndpointImplBase.java:1187)

    at org.apache.tomcat.websocket.WsRemoteEndpointImplBase.sendString(WsRemoteEndpointImplBase.java:190)

    at org.apache.tomcat.websocket.WsRemoteEndpointBasic.sendText(WsRemoteEndpointBasic.java:37)

    at cn.zhonya.WXTalkDome.webSocket.MyWebSocket.sendMessage(MyWebSocket.java:107)

    at cn.zhonya.WXTalkDome.webSocket.MyWebSocket.onMessage(MyWebSocket.java:80)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

    at java.lang.reflect.Method.invoke(Method.java:498)

    at org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBase.onMessage(PojoMessageHandlerWholeBase.java:80)

    at org.apache.tomcat.websocket.WsFrameBase.sendMessageText(WsFrameBase.java:399)

    at org.apache.tomcat.websocket.server.WsFrameServer.sendMessageText(WsFrameServer.java:106)

    at org.apache.tomcat.websocket.WsFrameBase.processDataText(WsFrameBase.java:500)

    at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:295)

    at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:131)

    at org.apache.tomcat.websocket.server.WsFrameServer.onDataAvailable(WsFrameServer.java:69)

    at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.upgradeDispatch(WsHttpUpgradeHandler.java:148)

    at org.apache.coyote.http11.upgrade.UpgradeProcessorInternal.dispatch(UpgradeProcessorInternal.java:54)

    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:53)

    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785)

    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1419)

    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:44)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)

    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)

    at java.lang.Thread.run(Thread.java:745)

    java+spring的socket代码如下:

    @ServerEndpoint(value = "/websocket2.do",configurator = SpringConfigurator.class)

    public class MyWebSocket {

    private static int onlineCount = 0;

    public MyWebSocket(){

    }

    @Autowired

    private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet();

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

    private Session session;

    /**

    * 链接建立成功调用的方法

    * @param session 可选的参数,session为与某个客户端连接的会话,需要通过它来给客户发送数据

    */

    @OnOpen

    public void onOpen(Session session, @PathParam("user") String user,@PathParam("uid") String uid){

    this.session = session;

    // session.getAttributes();

    logger.info("——————————————");

    logger.info("——————————————");

    logger.info("——————————————");

    logger.info("——————————————");

    JSONObject s = new JSONObject(session);

    String str= session.getQueryString();

    String [] strs = str.split("&");

    int slen = strs.length;

    for(String quey:strs){

    String [] q = quey.split("=");

    System.out.println("sing:"+q[0]+" value:"+q[1]);

    }

    logger.info("webSocketSet————————:"+s.toString());

    logger.info("——————————————");

    logger.info("——————————————");

    logger.info("——————————————");

    webSocketSet.add(this);//加入set中

    addOnlineCount();//在线人数加1

    System.out.println("有新链接加入!当前在线人数为:"+getOnlineCount()+" user:"+user+" uid:"+uid);

    }

    /**

    * 连接关闭调用的方法

    */

    @OnClose

    public void onClose(){

    webSocketSet.remove(this);//从set中删除

    subOnlineCount();

    System.out.println("有一个连接关闭!当前在线人数为:"+getOnlineCount());

    }

    @OnMessage

    public void onMessage(String message,Session session){

    System.out.println("来自客户端的消息:"+message);

    //群发消息

    for(MyWebSocket item:webSocketSet){

    try{

    if(item.session == session){

    // item.sendMessage("

    我说:"+message+" 当前在线人数:"+getOnlineCount()+"

    ");

    item.sendMessage(message);

    }else{

    item.sendMessage("

    "+message+" 当前在线人数:"+getOnlineCount()+"

    ");

    }

    }catch (IOException e){

    e.printStackTrace();

    continue;

    }

    }

    }

    @OnError

    public void onError(Session session,Throwable error){

    System.out.println("发生错误");

    error.printStackTrace();

    }

    /**

    * 这个方法与上面几个方法不一样,没有用注解,根据自己需要添加的方法

    * @param message

    */

    private void sendMessage(String message) throws IOException {

    //保存到数据库

    // Content content = new Content();

    // content.setContent(message);

    // content.setCreateDate(StringUtilZ.getTimestampOfNow("yyyy-MM-dd HH:mm:ss"));

    this.session.getBasicRemote().sendText(message);

    }

    public static synchronized int getOnlineCount(){

    return onlineCount;

    }

    public static synchronized void addOnlineCount() {

    MyWebSocket.onlineCount++;

    }

    private static synchronized void subOnlineCount(){

    MyWebSocket.onlineCount--;

    }

    }

    springmvc自身的那个文件比较多就不多贴了,暂时贴下那个139行上下的内容

    public void broadcast(final TextMessage message)throws IOException {

    Iterator> it = userSocketSessionMap

    .entrySet().iterator();

    //多线程群发

    while(it.hasNext()){

    final Map.Entry entry = it.next();

    if(entry.getValue().isOpen()){

    new Thread(new Runnable() {

    public void run() {

    try{

    if(entry.getValue().isOpen()){

    entry.getValue().sendMessage(message);

    }

    } catch (IOException e){

    e.printStackTrace();

    }

    }

    }).start();

    }

    }

    }

    这两种方法在普通WebSocket中都没问题,换到微信小程序就只能接受客户端消息,没办法将消息从服务器传到客户端。怀疑是不是那个session的问题啊,在小程序中使用获取到的session就是空的了。

    展开全文
  • 类似于http请求中的 request.getHeader("Referer"); 在websocket的onopen 方法中有没有能够获取的方法
  • <div><p>看代码好像是把swoole_websocket_server 和 fd对象放到了Request,但是我尝试获取获取不到</p><p>该提问来源于开源项目:garveen/laravoole</p></div>
  • <p>2.I need to send signedXml to another server via websocket <p>3.Save result (success or error) <p>4.Close connection <p>Every HTTP request will open connection, send 1 message, get 1 result and ...
  • springboot/spring4.0获取websocket请求ip

    千次阅读 2019-04-11 21:32:00
    众所周知,JSR-356对websocket的支持是通过http ugrade...所以需要通过WebFilter的方式在HTTPSession中放入,在握手的时候使用modifyHandshake获取IP。 具体步骤 在Filter中request.getSession() ,然后将HttpSer...

    众所周知,JSR-356对websocket的支持是通过http ugrade上来的,打断点可以看到调用栈,而标准的Session(WebSocketSession) 在规范中并没有ip。所以需要通过WebFilter的方式在HTTPSession中放入,在握手的时候使用modifyHandshake获取IP。

    具体步骤

    1. 在Filter中request.getSession() ,然后将HttpServletRequet.getRemoteAddr()存入map。
    2. 继承ServerEndpointConfig.Configurator,重写modifyHandshake方法。将 HTTPSession的值写入ServerEndpointConfig.UserProperties中。
    3. @ServerEndPoint(config=你刚刚继承的Configurator类。

      具体代码

    package com.app.modular.filter;
    
    import org.springframework.core.annotation.Order;
    
    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import java.io.IOException;
    
    @javax.servlet.annotation.WebFilter(filterName = "sessionFilter",urlPatterns = "/*")
    @Order(1)
    public class WebFilter implements Filter {
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            HttpServletRequest req= (HttpServletRequest) request;
            req.getSession().setAttribute("ip",req.getRemoteHost());
            chain.doFilter(request,response);
        }
    }
    package com..app.config;
    
    import javax.servlet.http.HttpSession;
    import javax.websocket.HandshakeResponse;
    import javax.websocket.server.HandshakeRequest;
    import javax.websocket.server.ServerEndpointConfig;
    import java.util.Enumeration;
    import java.util.Map;
    
    public class WebSocketConfigurator extends ServerEndpointConfig.Configurator {
            public static final String HTTP_SESSION_ID_ATTR_NAME = "HTTP.SESSION.ID";
    
            @Override
            public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
    
                    Map<String, Object> attributes = sec.getUserProperties();
                    HttpSession session = (HttpSession) request.getHttpSession();
                    if (session != null) {
                        attributes.put(HTTP_SESSION_ID_ATTR_NAME, session.getId());
                        Enumeration<String> names = session.getAttributeNames();
                        while (names.hasMoreElements()) {
                            String name = names.nextElement();
                            attributes.put(name, session.getAttribute(name));
                        }
    
                    }
            }
        }
    @ServerEndpoint(value = "/mysocket",configurator = WebSocketConfigurator.class)
    @Controller
    public class AppEntryPoint {
     @OnMessage
        public String msg(String msg, Session session) {
            log.info("收到消息" + msg);
        }
    }

    别忘了在启动类上打注解扫描Filter@ServletComponentScan(basePackages = {"com.aaa"})

    原文https://stackoverflow.com/questions/22880055/jsr-356-websockets-with-tomcat-how-to-limit-connections-within-single-ip-addre

    转载于:https://www.cnblogs.com/imjamin/p/10692742.html

    展开全文
  • public function onOpen(\swoole_websocket_server $server, \swoole_http_request $request) { // 在触发onOpen事件之前Laravel的生命周期已经完结,所以Laravel的Request是可读的,Session是可...
  • jsp获取websocket的远程服务器地址

    千次阅读 2015-12-07 11:16:31
    <%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";//远程ip地址String webPath = request.getLocalAddr()+...
  • <p>request exceeded the limit of 10 internal redirects due to probable configuration error. use 'limitinternalrecursion' to increase the limit if necessary. use 'loglevel debug' to get a backtrace. ...
  • 自己在用spring的websocket的时候,在request获取session的时候一直是null,后来发现是自己把自己坑了 代码是这样的,自己是新手,参照网上写的,本来用的没什么问题,做的东东能两个人相互聊天还高兴了好久,...
  • https://blog.csdn.net/panda929/article/details/52872128自己在用spring的websocket的时候,在request获取session的时候一直是null,后来发现是自己把自己坑了代码是这样的,自己是新手,参照网上写的,本来用的没...
  • 初识WebSocket

    2016-09-18 18:55:00
    但是随着互联 网的发展,浏览器与服务端进行双向通信需求的增加,长轮询向服务器以获取最新数据并实现推送效果的方式已经越来越不能满足我们。Html5标准的制定,也 为我们提供了浏览器与服务端的双工通信协议...
  • * 获取请求中的url */ public static String getUrl(ServerHttpRequest serverHttpRequest) { HttpServletRequest request = ((ServletServerHttpRequest) serverHttpRequest).getServlet...
  • 资源本人已整合,只需要下载解压至jmeter安装目录lib/ext即可,包含功能 ...WebSocket request-response Sampler 发送消息并获取返回消息 WebSocket Ping/Pong 发送心跳包 WebSocket Close 关闭连接
  • 但是随着互联网的发展,浏览器与服务端进行双向通信需求的增加,长轮询向服务器以获取最新数据并实现推送效果的方式已经越来越不能满足我们。Html5标准的制定,也为我们提供了浏览器与服务端的双工通信协议WebSocket...
  • 这个Request-Response的关系是无法改变的。对于一般的网页浏览和访问当然没问题,一旦我们需要服务端主动向客户端发送消息时就麻烦了,因为此前的TCP连接已经释放,根本找不到客户端在哪。为了能及时从服务器获取...
  • WebSocket 和 AJAX 比较

    千次阅读 2018-01-10 21:45:44
    这个Request-Response的关系是无法改变的。对于一般的网页浏览和访问当然没问题,一旦我们需要服务端主动向客户端发送消息时就麻烦了,因为此前的TCP连接已经释放,根本找不到客户端在哪。 为了能及时从服务器获取...
  • 网络api downloadFile接口 官方描述 ... 下面实现了文件的下载和下载过程中部分参数的获取,使用的是downloadFile接口 <view> <button bindtap="dow...
  • 当浏览器第一次访问的时候,request.getSession(false),如果之前没有获取到session,那么这个方法就会返回null,但是又会马上建立session。所以当第二次访问再request.getSession(false),就会获取到之前创建的...
  • 您可以通过http post request从AWS lambda function http post request新消息,并在客户端上以websocket消息的形式接收它们。 安装它 npm i aws-mqtt-client --save 基本用法 创建一个IAM角色并分配预定义的...

空空如也

空空如也

1 2 3 4 5 6
收藏数 106
精华内容 42
关键字:

websocket获取request