java WebSocket的實現(xiàn)以及Spring WebSocket示例代碼
開始學(xué)習(xí)WebSocket,準備用它來實現(xiàn)一個在頁面實時輸出log4j的日志以及控制臺的日志。
首先知道一些基礎(chǔ)信息:
1.java7 開始支持WebSocket,并且只是做了定義,并未實現(xiàn)
2.tomcat7及以上,jetty 9.1及以上實現(xiàn)了WebSocket,其他容器沒有研究
3.spring 4.0及以上增加了WebSocket的支持
4.spring 支持STOMP協(xié)議的WebSocket通信
5.WebSocket 作為java的一個擴展,它屬于javax包目錄下,通常需要手工引入該jar,以tomcat為例,可以在 tomcat/lib 目錄下找到 websocket-api.jar
開始實現(xiàn)
先寫一個普通的WebSocket客戶端,直接引入tomcat目錄下的jar,主要的jar有:websocket-api.jar、tomcat7-websocket.jar
public static void f1() { try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); // 獲取WebSocket連接器,其中具體實現(xiàn)可以參照websocket-api.jar的源碼,Class.forName("org.apache.tomcat.websocket.WsWebSocketContainer"); String uri = "ws://localhost:8081/log/log"; Session session = container.connectToServer(Client.class, new URI(uri)); // 連接會話 session.getBasicRemote().sendText("123132132131"); // 發(fā)送文本消息 session.getBasicRemote().sendText("4564546"); } catch (Exception e) { e.printStackTrace(); } }
其中的URL格式必須是ws開頭,后面接注冊的WebSocket地址
Client.java 是用于收發(fā)消息
@ClientEndpoint public class Client { @OnOpen public void onOpen(Session session) { System.out.println("Connected to endpoint: " + session.getBasicRemote()); } @OnMessage public void onMessage(String message) { System.out.println(message); } @OnError public void onError(Throwable t) { t.printStackTrace(); } }
到這一步,客戶端的收發(fā)消息已經(jīng)完成,現(xiàn)在開始編寫服務(wù)端代碼,用Spring 4.0,其中pom.xml太長就不貼出來了,會用到j(luò)ackson,spring-websocket,spring-message
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.socket.WebSocketHandler; 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 com.gionee.log.client.LogWebSocketHandler; /** * 注冊普通WebScoket * @author PengBin * @date 2016年6月21日 下午5:29:00 */ @Configuration @EnableWebMvc @EnableWebSocket public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer { @Autowired @Lazy private SimpMessagingTemplate template; /** {@inheritDoc} */ @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(logWebSocketHandler(), "/log"); // 此處與客戶端的 URL 相對應(yīng) } @Bean public WebSocketHandler logWebSocketHandler() { return new LogWebSocketHandler(template); } }
import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; /** * * @author PengBin * @date 2016年6月24日 下午6:04:39 */ public class LogWebSocketHandler extends TextWebSocketHandler { private SimpMessagingTemplate template; public LogWebSocketHandler(SimpMessagingTemplate template) { this.template = template; System.out.println("初始化 handler"); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String text = message.getPayload(); // 獲取提交過來的消息 System.out.println("handMessage:" + text); // template.convertAndSend("/topic/getLog", text); // 這里用于廣播 session.sendMessage(message); } }
這樣,一個普通的WebSocket就完成了,自己還可以集成安全控制等等
Spring還支持一種注解的方式,可以實現(xiàn)訂閱和廣播,采用STOMP格式協(xié)議,類似MQ,其實應(yīng)該就是用的MQ的消息格式,下面是實現(xiàn)
同樣客戶端:
public static void main(String[] args) { try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); String uri = "ws://localhost:8081/log/hello/hello/websocket"; Session session = container.connectToServer(Client.class, new URI(uri)); char lf = 10; // 這個是換行 char nl = 0; // 這個是消息結(jié)尾的標記,一定要 StringBuilder sb = new StringBuilder(); sb.append("SEND").append(lf); // 請求的命令策略 sb.append("destination:/app/hello").append(lf); // 請求的資源 sb.append("content-length:14").append(lf).append(lf); // 消息體的長度 sb.append("{\"name\":\"123\"}").append(nl); // 消息體 session.getBasicRemote().sendText(sb.toString()); // 發(fā)送消息 Thread.sleep(50000); // 等待一小會 session.close(); // 關(guān)閉連接 } catch (Exception e) { e.printStackTrace(); } }
這里一定要注意,換行符和結(jié)束符號,這個是STOMP協(xié)議規(guī)定的符號,錯了就不能解析到
服務(wù)端配置
/** * 啟用STOMP協(xié)議WebSocket配置 * @author PengBin * @date 2016年6月24日 下午5:59:42 */ @Configuration @EnableWebMvc @EnableWebSocketMessageBroker public class WebSocketBrokerConfig extends AbstractWebSocketMessageBrokerConfigurer { /** {@inheritDoc} */ @Override public void registerStompEndpoints(StompEndpointRegistry registry) { System.out.println("注冊"); registry.addEndpoint("/hello").withSockJS(); // 注冊端點,和普通服務(wù)端的/log一樣的 // withSockJS()表示支持socktJS訪問,在瀏覽器中使用 } /** {@inheritDoc} */ @Override public void configureMessageBroker(MessageBrokerRegistry config) { System.out.println("啟動"); config.enableSimpleBroker("/topic"); // config.setApplicationDestinationPrefixes("/app"); // 格式前綴 } } Controller @Controller public class LogController { private SimpMessagingTemplate template; @Autowired public LogController(SimpMessagingTemplate template) { System.out.println("init"); this.template = template; } @MessageMapping("/hello") @SendTo("/topic/greetings") // 訂閱 public Greeting greeting(HelloMessage message) throws Exception { System.out.println(message.getName()); Thread.sleep(3000); // simulated delay return new Greeting("Hello, " + message.getName() + "!"); } }
到這里就已經(jīng)全部完成。
template.convertAndSend("/topic/greetings", "通知"); // 這個的意思就是向訂閱了/topic/greetings進行廣播
對于用socktJS連接的時候會有一個訪問 /info 地址的請求
如果在瀏覽器連接收發(fā)送消息,則用sockt.js和stomp.js
function connect() { var socket = new SockJS('/log/hello/hello'); stompClient = Stomp.over(socket); stompClient.connect({}, function(frame) { setConnected(true); console.log('Connected: ' + frame); stompClient.subscribe('/topic/greetings', function(greeting) { showGreeting(JSON.parse(greeting.body).content); }); }); } function disconnect() { if (stompClient != null) { stompClient.disconnect(); } setConnected(false); console.log("Disconnected"); } function sendName() { var name = document.getElementById('name').value; stompClient.send("/app/hello", {}, JSON.stringify({ 'name' : name })); }
在瀏覽器中可以看到請求返回101狀態(tài)碼,意思就是切換協(xié)議
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 使用Spring Boot搭建Java web項目及開發(fā)過程圖文詳解
- springboot+webmagic實現(xiàn)java爬蟲jdbc及mysql的方法
- Java中Spring WebSocket詳解
- webuploader在springMVC+jquery+Java開發(fā)環(huán)境下的大文件分片上傳的實例代碼
- java web SpringMVC后端傳json數(shù)據(jù)到前端頁面實例代碼
- C程序函數(shù)調(diào)用&系統(tǒng)調(diào)用
- JavaWeb項目中springmvc和tomcat對靜態(tài)文件的處理
- Java Spring WEB應(yīng)用實例化如何實現(xiàn)
相關(guān)文章
Springboot+MDC+traceId日志中打印唯一traceId
本文主要介紹了Springboot+MDC+traceId日志中打印唯一traceId,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-10-10Jpa 如何使用@EntityListeners 實現(xiàn)實體對象的自動賦值
這篇文章主要介紹了Jpa 如何使用@EntityListeners 實現(xiàn)實體對象的自動賦值,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08基于Properties實現(xiàn)配置數(shù)據(jù)庫驅(qū)動
這篇文章主要介紹了基于Properties實現(xiàn)配置數(shù)據(jù)庫驅(qū)動,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-05-05Java UrlRewriter偽靜態(tài)技術(shù)運用深入分析
通常我們?yōu)榱烁玫木徑夥?wù)器壓力,和增強搜索引擎的友好面,都將文章內(nèi)容生成靜態(tài)頁面,這就產(chǎn)生了偽靜態(tài)技術(shù),也就是我們常說的Url Rewriter重寫技術(shù)2012-12-12詳解Java并發(fā)工具類之CountDownLatch和CyclicBarrier
在JDK的并發(fā)包中,有幾個非常有用的并發(fā)工具類,它們分別是:CountDownLatch、CyclicBarrier、Semaphore和Exchanger,本文主要來講講其中CountDownLatch和CyclicBarrier的使用,感興趣的可以了解一下2023-06-06