SSM项目中引入websocket后,websocket有时能够正常运行,有时候无法正常启动 5C

SSM项目中引入websocket后,websocket有时能够正常运行,有时候无法正常启动,配置是相同的,并没有更改。
IDE:IDEA
jdk:1.8
tomcat:8.5

public class WebSocketFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.startWebsocketInstantMsg();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    }

    @Override
    public void destroy() {

    }

    public void startWebsocketInstantMsg(){
        WebSocketImpl.DEBUG=false;
        WebServer webServer = new WebServer(6004);
        webServer.onStart();
    }
}

webserver.class类

public class WebServer extends WebSocketServer {

    public WebServer(int port) {
        super(new InetSocketAddress(port));
    }

    public WebServer(InetSocketAddress address) {
        super(address);
    }

    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
        System.out.println("onOpen");
    }

    @Override
    public void onClose(WebSocket webSocket, int i, String s, boolean b) {
        //断开连接时候触发代码
        userLeave(webSocket);
        System.out.println(s);
        System.out.println("onClose");
    }

    @Override
    public void onMessage(WebSocket webSocket, String s) {
        System.out.println(s);
        System.out.println("onMessage");
        if(null != s){
            String userName = s.replaceFirst("online", s);//用户名
            userJoin(webSocket,userName);//用户加入
        }
        WsPool.sendMessageToUser(webSocket,"你好,客户端");
    }

    @Override
    public void onError(WebSocket webSocket, Exception e) {
        //错误时候触发的代码
        System.out.println("on error");
        e.printStackTrace();
    }

    @Override
    public void onStart() {
        System.out.println("onStart");
        new Thread( this ).start();
    }

    /**
     * 去除掉失效的websocket链接
     * @param conn
     */
    private void userLeave(WebSocket conn){
        WsPool.removeUser(conn);
    }
    /**
     * 将websocket加入用户池
     * @param conn
     * @param userName
     */
    private void userJoin(WebSocket conn,String userName){
        WsPool.addUser(userName, conn);
    }
}

maven配置

<dependency>
      <groupId>javax.websocket</groupId>
      <artifactId>javax.websocket-api</artifactId>
      <version>1.1</version>
    </dependency>
    <dependency>
      <groupId>org.java-websocket</groupId>
      <artifactId>Java-WebSocket</artifactId>
      <version>1.3.7</version>
    </dependency>

web.xml 配置

<filter>
        <filter-name>webSocketFilter</filter-name>
        <filter-class>com.platform.interceptor.WebSocketFilter</filter-class>
    </filter>

1个回答

无法启动具体什么情况,错误信息有吗

qq_38773852
qq_38773852 没有错误信息,刚刚发现是Filter在tomcat启动时没有被初始化,所以没有启动websocket
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐