Java에서 웹소켓 메시지 푸시 구현 코드

하나.서비스 계층

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();
          }
        }
      }
    }
  }
}
2.프런트 인터페이스 감청

<!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>
웹 주의.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>
위에서 말한 것은 여러분에게 소개된 자바에서 웹소켓 메시지를 푸시하는 실현 코드입니다. 여러분에게 도움이 되었으면 합니다. 만약에 궁금한 것이 있으면 저에게 메시지를 남겨 주십시오. 편집자는 제때에 여러분에게 회답할 것입니다.여기에서도 저희 사이트에 대한 지지에 감사드립니다!

좋은 웹페이지 즐겨찾기