为了便于调试与展示效果,写一个控制层,用于推送消息
package com.renewable.center.warning.controller.websocket; import com.renewable.terminal.terminal.common.ServerResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.io.IOException; /** * @Description: 用于测试WebsocketServer * @Author: jarry */ @Controller @RequestMapping("/websocket/test/") public class WarningWebsocketController { @GetMapping("link.do") @ResponseBody public ServerResponse link(@RequestParam(name = "sid") int sid){ return ServerResponse.createBySuccessMessage("link : "+sid); } /** * 调用WarningWebsocketServer的消息推送方法,从而进行消息推送 * @param sid 连接WarningWebsocketServer的前端的唯一标识。如果sid为空,即表示向所有连接WarningWebsocketServer的前端发送相关消息 * @param message 需要发送的内容主体 * @return */ @ResponseBody @RequestMapping("push.do") public ServerResponse pushToWeb(@RequestParam(name = "sid", defaultValue = "") String sid, @RequestParam(name = "message") String message) { WarningWebSocketServer.sendInfo(sid, message); return ServerResponse.createBySuccessMessage(message+"@"+sid+" has send to target."); } } WesocketTestIndex这里建立了一个B端页面,用于与S端进行交互,演示。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>WebsocketTestIndex</title> </head> <body> <h1>Websocket Test</h1> </body> </html> 效果展示再次强调,图片很大很清晰。如果看不清楚,请单独打开图片。
B端网页初始化: 调用S端WarningWebsocketController下pushToWeb()接口,对sid=2的B端发送消息: B端网页接收到专门发给sid=2的消息后的效果: 调用S端WarningWebsocketController下pushToWeb()接口,所有连接该websocket的B端群发消息: B端网页接收到群发消息后的效果: