<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>
新建WebSocket配置类
package com.example.demo.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;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;/*** Created by dingshuo on 2017/5/18.*/@Configuration@EnableWebSocketpublic class WebsocketConfig implements WebSocketConfigurer{@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {webSocketHandlerRegistry.addHandler(myHandler(),"/ws").setAllowedOrigins("*").withSockJS();}@Beanpublic WebSocketHandler myHandler(){return new com.example.demo.config.WebSocketHandler();}}
根据配置类中的Handler定义,进行具体代码编写
package com.example.demo.config;import org.springframework.stereotype.Component;import org.springframework.web.socket.CloseStatus;import org.springframework.web.socket.TextMessage;import org.springframework.web.socket.WebSocketMessage;import org.springframework.web.socket.WebSocketSession;import org.springframework.web.socket.handler.TextWebSocketHandler;import java.util.HashMap;import java.util.Map;import java.util.UUID;/*** Created by dingshuo on 2017/5/18.*/@Componentpublic class WebSocketHandler extends TextWebSocketHandler{public static final Map<Object, WebSocketSession> userSocketSessionMap;static {userSocketSessionMap = new HashMap<Object, WebSocketSession>();}@Overridepublic void afterConnectionEstablished(WebSocketSession session) throws Exception {userSocketSessionMap.put(UUID.randomUUID(),session);System.out.println("建立连接完成");}@Overridepublic void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {switch (message.getPayload().toString()){case "1":sendMsg(session,new TextMessage("A"));break;case "2":sendMsg(session,new TextMessage("B"));break;}System.out.println("处理消息");}@Overridepublic void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {System.out.println("处理消息传出错误");}@Overridepublic void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {System.out.println("处理连接关闭");}private void sendMsg(WebSocketSession session,TextMessage message) throws Exception {for (int i=0;i<100;i++){Thread.sleep(1000);session.sendMessage(message);}}}
在Handler里可以看出每个连接的连接-接收消息-关闭连接等过程,只需要在相应的函数中完成具体方法即可
此处简单模拟,客户端连接后,发送一个连接字符,然后服务器根据连接字符不断的推送消息(这里是发送“1”或“2”)
新建一个测试用的html静态页面(这里引用了sockjs),代码是抄网上的。。。
注意修改url地址信息
<!doctype html><html><head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><script src="http://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js"></script><style>.box {width: 300px;float: left;margin: 0 20px 0 20px;}.box div, .box input {border: 1px solid;-moz-border-radius: 4px;border-radius: 4px;width: 100%;padding: 0px;margin: 5px;}.box div {border-color: grey;height: 300px;overflow: auto;}.box input {height: 30px;}h1 {margin-left: 30px;}body {background-color: #F0F0F0;font-family: "Arial";}</style></head><body lang="en"><h1>Index</h1><div id="first" class="box"><div></div><form><input autocomplete="off" value="Type here..."></input></form></div><script>var sockjs_url = 'http://127.0.0.1:8080/ws';var sockjs = new SockJS(sockjs_url);$('#first input').focus();var div = $('#first div');var inp = $('#first input');var form = $('#first form');var print = function(m, p) {p = (p === undefined) ? '' : JSON.stringify(p);div.append($("<code>").text(m + ' ' + p));div.append($("<br>"));div.scrollTop(div.scrollTop()+10000);};sockjs.onopen = function() {print('[*] open', sockjs.protocol);};sockjs.onmessage = function(e) {print('[.] message', e.data);};sockjs.onclose = function() {print('[*] close');};form.submit(function() {print('[ ] sending', inp.val());sockjs.send(inp.val());inp.val('');return false;});</script></body></html>