zoukankan      html  css  js  c++  java
  • (网页)websocket后台调用Service层

    百度论坛里面有很多好的方法,借鉴.

          重点:因为项目是StringBoot所以我用的是下面的方法很好使:

      

    Service.... service = (Service....) ContextLoader.getCurrentWebApplicationContext().getBean(Service.....class);
     ContextLoader.getCurrentWebApplicationContext().getBean(BeanName)

    下面的是其他人的回答,第一个有用了,其他的先看看吧:

    例子1:

    当时 做开发的时候 在2015年7月份的时候 碰到跟楼主一样的问题
    网上找遍 都找不到自动注入的方法,最后没办法,在websocket的握手驱动类里面 返回一个能拿到注入权限的类,然后利用这个类 实现websocket接口 拿到自动注入权限。绕了他娘的好大一圈。

    例子2:

    今天也遇到了这个问题,找了半天也没找到自动注入的方法。最后选择的最原始的方法解决。下面是我的代码
    @Component
    @Lazy(false)
    public class ApplicationContextRegister implements ApplicationContextAware {
    
        private static ApplicationContext APPLICATION_CONTEXT;
    
        /**
         * 设置spring上下文  *  * @param applicationContext spring上下文  * @throws BeansException
         */
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            APPLICATION_CONTEXT = applicationContext;
        }
    
        public static ApplicationContext getApplicationContext() {
            return APPLICATION_CONTEXT;
        }
    }
    
    webScoket的注入service
      {
            ApplicationContext act = ApplicationContextRegister.getApplicationContext();
            userService=act.getBean(UserService.class);
            chatService=act.getBean(ChatService.class);
        }

    举个自己写过的例子:html+js+后台

    <div class="View" style=" 100%;height:100%;">
                                        <h1>Java后端WebSocket的Tomcat实现</h1>
                                         Welcome<br/><input id="text" type="text"/>
                                         <button onclick="send()">发送消息</button>
                                         <hr/>
                                         <button onclick="closeWebSocket()">关闭WebSocket连接</button>
                                         <hr/>
                                         <div id="message"></div>
                                    </div>

    js:

         var websocket = null;
         //判断当前浏览器是否支持WebSocket
         if ('WebSocket' in window) {
             websocket = new WebSocket("ws://localhost:8084/websocket");
         }
         else {
             alert('当前浏览器 Not support websocket')
         }
     
         //连接发生错误的回调方法
         websocket.onerror = function () {
             setMessageInnerHTML("WebSocket连接发生错误");
         };
     
         //连接成功建立的回调方法
         websocket.onopen = function () {
             setMessageInnerHTML("WebSocket连接成功");
             
             websocket.send(sessionStorage.getItem("dealerId"));
         }
     
         //接收到消息的回调方法
         websocket.onmessage = function (event) {
             setMessageInnerHTML(event.data);
         }
     
         //连接关闭的回调方法
         websocket.onclose = function () {
             setMessageInnerHTML("WebSocket连接关闭");
         }
     
         //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
         window.onbeforeunload = function () {
             closeWebSocket();
         }
     
         //将消息显示在网页上
         function setMessageInnerHTML(innerHTML) {
             document.getElementById('message').innerHTML += innerHTML + '<br/>';
         }
     
         //关闭WebSocket连接
         function closeWebSocket() {
             websocket.close();
         }
     
         //发送消息
         function send() {
             //var message = document.getElementById('text').value;
             websocket.send(sessionStorage.getItem("dealerId"));
         }

    后台:

    <dependency>
                <groupId>javax.websocket</groupId>
                <artifactId>javax.websocket-api</artifactId>
                <version>1.1</version>
                <scope>provided</scope>
            </dependency>
    参考,如果缺少包的话,还是的百度。
    import java.util.concurrent.CopyOnWriteArraySet;
    
    import javax.annotation.Resource;
    import javax.websocket.*;
    import javax.websocket.server.ServerEndpoint;
    
    import org.springframework.stereotype.Component;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.context.ContextLoader;
    
    import jy.api.form.JyChangeInStatusHistoryApiForm;
    import jy.component.BaseController;
    import jy.component.ServiceFacade;
    import jy.service.JyChangeInStatusHistoryService;
    
    
    @Component
    @ServerEndpoint("/websocket")
    public class WebsocketTest extends BaseController{
        
        public WebsocketTest(){
            System.out.println("WebsocketTest..");
        }
    
        @OnOpen
        public void onopen(Session session){
            System.out.println("连接成功");
            try {
                session.getBasicRemote().sendText("hello client...");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        @OnClose
        public void onclose(Session session){
            System.out.println("close....");
        } 
        
         @OnMessage      
        public void onsend(Session session,String msg){
            try {
                System.out.println('就是客户端传到后台的值'+msg);
                Service... service =  ContextLoader.getCurrentWebApplicationContext().getBean(service....class);
                session.getBasicRemote().sendText(""+传到HTML网页上的值);
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
        }
    }

    之前老报这个错就是调Service层的时候报的:

    }                                                                                                                                                                                  
    09:34:32.179 [http-bio-8084-exec-9] ERROR o.a.t.w.pojo.PojoEndpointBase - No error handling configured for [jy.websocket.WebsocketTest] and the following error occurred           
    java.lang.IllegalArgumentException: java.lang.reflect.InvocationTargetException                                                                                                    
            at org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBase.onMessage(PojoMessageHandlerWholeBase.java:84)                                                             
            at org.apache.tomcat.websocket.WsFrameBase.sendMessageText(WsFrameBase.java:369)                                                                                           
            at org.apache.tomcat.websocket.WsFrameBase.processDataText(WsFrameBase.java:468)                                                                                           
            at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:272)                                                                                               
            at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:116)                                                                                        
            at org.apache.tomcat.websocket.server.WsFrameServer.onDataAvailable(WsFrameServer.java:54)                                                                                 
            at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler$WsReadListener.onDataAvailable(WsHttpUpgradeHandler.java:192)                                                   
            at org.apache.coyote.http11.upgrade.AbstractServletInputStream.onDataAvailable(AbstractServletInputStream.java:178)                                                        
            at org.apache.coyote.http11.upgrade.AbstractProcessor.upgradeDispatch(AbstractProcessor.java:92)                                                                           
            at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:601)                                                                         
            at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)                                                                                        
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)                                                                                         
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)                                                                                         
            at java.lang.Thread.run(Thread.java:745)                                                                                                                                   
    Caused by: java.lang.reflect.InvocationTargetException: null                                                                                                                       
            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:483)                                                                                                                        
            at org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBase.onMessage(PojoMessageHandlerWholeBase.java:80)                                                             
            ... 13 common frames omitted                                                                                                                                               
    Caused by: java.lang.NullPointerException: null                                                                                                                                    
            at jy.websocket.WebsocketTest.onsend(WebsocketTest.java:53)                                                                                                                
            ... 18 common frames omitted                                                                                                                                               
    Long.valueOf(msg)3465007                                                                                                                                                           
    09:34:32.188 [http-bio-8084-exec-9] ERROR o.a.t.w.pojo.PojoEndpointBase - No error handling configured for [jy.websocket.WebsocketTest] and the following error occurred           
    java.lang.IllegalArgumentException: java.lang.reflect.InvocationTargetException                                                                                                    
            at org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBase.onMessage(PojoMessageHandlerWholeBase.java:84)                                                             
            at org.apache.tomcat.websocket.WsFrameBase.sendMessageText(WsFrameBase.java:369)                                                                                           
            at org.apache.tomcat.websocket.WsFrameBase.processDataText(WsFrameBase.java:468)                                                                                           
            at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:272)                                                                                               
            at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:116)                                                                                        
            at org.apache.tomcat.websocket.server.WsFrameServer.onDataAvailable(WsFrameServer.java:54)                                                                                 
            at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler$WsReadListener.onDataAvailable(WsHttpUpgradeHandler.java:192)                                                   
            at org.apache.coyote.http11.upgrade.AbstractServletInputStream.onDataAvailable(AbstractServletInputStream.java:178)                                                        
            at org.apache.coyote.http11.upgrade.AbstractProcessor.upgradeDispatch(AbstractProcessor.java:92)                                                                           
            at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:601)                                                                         
            at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)                                                                                        
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)                                                                                         
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)                                                                                         
            at java.lang.Thread.run(Thread.java:745)                                                                                                                                   
    Caused by: java.lang.reflect.InvocationTargetException: null                                                                                                                       
            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:483)                                                                                                                        
            at org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBase.onMessage(PojoMessageHandlerWholeBase.java:80)                                                             
            ... 13 common frames omitted                                                                                                                                               
    Caused by: java.lang.NullPointerException: null                                                                                                                                    
            at jy.websocket.WebsocketTest.onsend(WebsocketTest.java:53)                                                                                                                
    

      

  • 相关阅读:
    C# 装箱原型
    C# 反射浅谈(一)
    javascript介绍(二)
    javascript介绍(一)
    C#中 托管资源和非托管资源
    varchar && nvarchar 闲谈
    高内聚&&低耦合
    【android】移植IOS视图响应陀螺仪交互行为
    【android】如何实现猿题库题目的排版
    开心工作标准的硬件环境
  • 原文地址:https://www.cnblogs.com/historylyt/p/8124720.html
Copyright © 2011-2022 走看看