温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

在Java项目中使用websocket实现消息推送功能

发布时间:2020-11-09 17:43:05 来源:亿速云 阅读:344 作者:Leah 栏目:编程语言

在Java项目中使用websocket实现消息推送功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

一.服务层

package com.demo.websocket;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Configuration
@EnableWebSocket
public class websocketListener implements WebSocketConfigurer, ServletContextListener{
  private ConcurrentLinkedQueue<WebSocketSession> sessions = new ConcurrentLinkedQueue<WebSocketSession>();
  private WebSocketHandlerTest handler;
  @Override
  public void contextDestroyed(ServletContextEvent arg0) {
    // TODO Auto-generated method stub
  }
  @Override
  public void contextInitialized(ServletContextEvent arg0) {
    // TODO Auto-generated method stub
  }
  @Override
  public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    handler = new WebSocketHandlerTest();
    registry.addHandler(handler, "/ws/notifymessage.ws");
    registry.addHandler(handler, "/ws/sockjs/notifymessage.ws").withSockJS();
    new Thread(handler).start();
  }
  class WebSocketHandlerTest extends TextWebSocketHandler implements Runnable{
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
      sessions.remove(session);
    }
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
      sessions.add(session);
    }
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
      super.handleTextMessage(session, message);
    }
    @Override
    public void run() {
      System.out.println("等待推送....");
      try {
        int i = 0;
        for (;;) {
          synchronized (this) {
            try {
              Thread.sleep(3000);
            } catch (InterruptedException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
          if(i%10==0){
            nofity("消息推送测试......");
            System.out.println("推送消息了....");
          }else{
            System.out.println("本次不推送消息了....");
          }
          i++;
        }
      } catch (IOException e) {
        e.printStackTrace();
        System.out.println("失败....");
      }
    }
    private void nofity(String message) throws IOException {
      Iterator<WebSocketSession> iterator = sessions.iterator();
      while (iterator.hasNext()) {
        WebSocketSession session = iterator.next();
        synchronized(session){
          if(session.isOpen()){
            session.sendMessage(new TextMessage(message));
          }else{
            iterator.remove();
          }
        }
      }
    }
  }
}

二.前台界面监听

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
websocket测试界面
</body>
<script type="text/javascript">
var websocketPath = "localhost:8080/demo-web";
if ('WebSocket' in window) {
  websocket = new WebSocket("ws://"+websocketPath+"/ws/notifymessage.ws");
} else if ('MozWebSocket' in window) {
  websocket = new MozWebSocket("ws://"+websocketPath+"/ws/notifymessage.ws");
} else {
  websocket = new SockJS("ws://"+websocketPath+"/ws/notifymessage.ws");
}
websocket.onopen = function (evnt) {
};
websocket.onmessage = function (evnt) {
  console.log(evnt);
};
websocket.onerror = function (evnt) {
};
websocket.onclose = function (evnt) {
}
</script>
</html>

注意web.xml中配置DispatcherServlet控制器

spring-servlet.xml空文件

<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>*.ws</url-pattern>
  </servlet-mapping>

看完上述内容,你们掌握在Java项目中使用websocket实现消息推送功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI