WebSocket 是 HTML5 開始提供的一種在單個 TCP 鏈接上進行全雙工通信的協議。javascript
WebSocket 使得客戶端和服務器之間的數據交換變得更加簡單,容許服務端主動向客戶端推送數據。在 WebSocket API 中,瀏覽器和服務器只須要完成一次握手,二者之間就直接能夠建立持久性的鏈接,並進行雙向數據傳輸。html
在 WebSocket API 中,瀏覽器和服務器只須要作一個握手的動做,而後,瀏覽器和服務器之間就造成了一條快速通道。二者之間就直接能夠數據互相傳送。前端
話很少說,立刻進入乾貨時刻。java
SpringBoot2.0對WebSocket的支持簡直太棒了,直接就有包能夠引入web
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
啓用WebSocket的支持也是很簡單,幾句代碼搞定spring
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * 開啓WebSocket支持 * @author zhengkai */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
由於WebSocket是相似客戶端服務端的形式(採用ws協議),那麼這裏的WebSocketServer其實就至關於一個ws協議的Controller直接@ServerEndpoint("/websocket")、@Component啓用便可,而後在裏面實現@OnOpen,@onClose,@onMessage等方法瀏覽器
import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import org.springframework.stereotype.Component; import cn.hutool.log.Log; import cn.hutool.log.LogFactory; import lombok.extern.slf4j.Slf4j; @ServerEndpoint("/websocket/{sid}") @Component public class WebSocketServer { static Log log=LogFactory.get(WebSocketServer.class); //靜態變量,用來記錄當前在線鏈接數。應該把它設計成線程安全的。 private static int onlineCount = 0; //concurrent包的線程安全Set,用來存放每一個客戶端對應的MyWebSocket對象。 private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>(); //與某個客戶端的鏈接會話,須要經過它來給客戶端發送數據 private Session session; //接收sid private String sid=""; /** * 鏈接創建成功調用的方法*/ @OnOpen public void onOpen(Session session,@PathParam("sid") String sid) { this.session = session; webSocketSet.add(this); //加入set中 addOnlineCount(); //在線數加1 log.info("有新窗口開始監聽:"+sid+",當前在線人數爲" + getOnlineCount()); this.sid=sid; try { sendMessage("鏈接成功"); } catch (IOException e) { log.error("websocket IO異常"); } } /** * 鏈接關閉調用的方法 */ @OnClose public void onClose() { webSocketSet.remove(this); //從set中刪除 subOnlineCount(); //在線數減1 log.info("有一鏈接關閉!當前在線人數爲" + getOnlineCount()); } /** * 收到客戶端消息後調用的方法 * * @param message 客戶端發送過來的消息*/ @OnMessage public void onMessage(String message, Session session) { log.info("收到來自窗口"+sid+"的信息:"+message); //羣發消息 for (WebSocketServer item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } } } /** * * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.error("發生錯誤"); error.printStackTrace(); } /** * 實現服務器主動推送 */ public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * 羣發自定義消息 * */ public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException { log.info("推送消息到窗口"+sid+",推送內容:"+message); for (WebSocketServer item : webSocketSet) { try { //這裏能夠設定只推送給這個sid的,爲null則所有推送 if(sid==null) { item.sendMessage(message); }else if(item.sid.equals(sid)){ item.sendMessage(message); } } catch (IOException e) { continue; } } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; } public static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; } }
至於推送新信息,能夠再本身的Controller寫個方法調WebSocketServer.sendInfo();便可安全
@Controller @RequestMapping("/checkcenter") public class CheckCenterController { //頁面請求 @GetMapping("/socket/{cid}") public ModelAndView socket(@PathVariable String cid) { ModelAndView mav=new ModelAndView("/socket"); mav.addObject("cid", cid); return mav; } //推送數據接口 @ResponseBody @RequestMapping("/socket/push/{cid}") public ApiReturnObject pushToWeb(@PathVariable String cid,String message) { try { WebSocketServer.sendInfo(message,cid); } catch (IOException e) { e.printStackTrace(); return ApiReturnUtil.error(cid+"#"+e.getMessage()); } return ApiReturnUtil.success(cid); } }
在頁面用js代碼調用socket,固然,太古老的瀏覽器是不行的,通常新的瀏覽器或者谷歌瀏覽器是沒問題的。springboot
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>菜鳥教程(runoob.com)</title> <script type="text/javascript"> function WebSocketTest() { if ("WebSocket" in window) { alert("您的瀏覽器支持 WebSocket!"); // 打開一個 web socket var ws = new WebSocket("ws://127.0.0.1:8080/websocket/1212"); ws.onopen = function() { // Web Socket 已鏈接上,使用 send() 方法發送數據 ws.send("發送數據"); alert("數據發送中..."); }; ws.onmessage = function (evt) { var received_msg = evt.data; alert(received_msg) alert("數據已接收..."); }; ws.onclose = function() { // 關閉 websocket alert("鏈接已關閉..."); }; } else { // 瀏覽器不支持 WebSocket alert("您的瀏覽器不支持 WebSocket!"); } } </script> </head> <body> <div id="sse"> <a href="javascript:WebSocketTest()">運行 WebSocket</a> </div> </body> </html>
一、啓動springboot項目。服務器
二、直接打開頁面test.html,點擊連接
三、服務端發送消息:
http://localhost:8080/checkcenter/socket/push/1212?message=xxxx