Java中websocket消息推送的實現(xiàn)代碼
更新時間:2017年02月13日 11:40:27 作者:tianzhongshan
這篇文章主要介紹了Java中websocket消息推送的實現(xiàn)代碼,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
一.服務層
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(); } } } } } }
二.前臺界面監(jiān)聽
<!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消息推送的實現(xiàn)代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
相關文章
IntelliJ?IDEA?2021.3?正式發(fā)布之支持遠程開發(fā)、IDE故障排查等多項優(yōu)化改進
IntelliJ?IDEA?2021.3?正式發(fā)布:支持遠程開發(fā)、IDE故障排查等多項優(yōu)化改進問題,在這個版本中的遠程開發(fā)還不是一個正式版本,而是BETA版,但通過這個BETA版本,也可以體驗IDEA“遠程開發(fā)”給我們帶來的全新體驗2021-12-12spring?boot集成jasypt?并實現(xiàn)自定義加解密的詳細步驟
由于項目中的配置文件?配置的地方過多,現(xiàn)將配置文件統(tǒng)一放到nacos上集中管理?且密碼使用加密的方式放在配置文件中,配置文件的加密使用加密庫jasypt,本文給大家介紹spring boot集成jasypt并實現(xiàn)自定義加解密,感興趣的朋友一起看看吧2023-08-08詳解Elasticsearch如何把一個索引變?yōu)橹蛔x
這篇文章主要為大家介紹了詳解Elasticsearch如何把一個索引變?yōu)橹蛔x示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02SpringBoot如何統(tǒng)一處理返回結果和異常情況
這篇文章主要介紹了SpringBoot如何統(tǒng)一處理返回結果和異常情況問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05