欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java中websocket消息推送的实现代码

程序员文章站 2024-03-31 19:12:46
一.服务层 package com.demo.websocket; import java.io.ioexception; import java.util....

一.服务层

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消息推送的实现代码,希望对大家有所帮助