springBoot 整合WebSocket

业务需求需要一个需要首页的控制台跟随数据试试变更 采用WebSocket 进行数据通知

1.SpringBoot WebSocket 依赖
springBoot 整合WebSocket_第1张图片
2.将webSocket 注入到spring 容器中 配置类

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter getServerEndpointExporter(){
        return new ServerEndpointExporter ();
    }

}
3.以下是Server端代码 userid 采用reset风格

@Component
@ServerEndpoint("/webSecketTest/sendMsg/{userid}")
public class WebSocketServer {
 public static Map mapsession = new HashMap();

/**

  • 建立连接
  • @param seesion
  • @param userid
    */
 @OnOpen
 public void onOpen(Session seesion, @PathParam("userid") String userid) {
  mapsession.put ( userid,seesion );
  System.out.println("===建立连接=====");
 }

 /**
  * 接收客户端传递的消息
  *
  * @param session
  * @param message
  * @param userid
  */

 @OnMessage
 public void onMessage(Session seesion, String message, @PathParam("userid") String userid) {
  mapsession.put ( userid,seesion );
  System.out.println("===onMessage==服务端接收到的客户端的消息===" + message);
 }

 /**
  * 当通道连接关闭的时候触发该方法
  *
  * @param session
  * @param userid
  */

@OnClose
public void onClose(Session session, @PathParam(“userid”) String userid) {
System.out.println("=onClose连接通道关闭");
//清除Session
mapsession.remove ( userid );
}


 /**
  * 通道发生错误的时候触发
  *
  * @param session
  * @param throwable
  * @param userid
  */
 @OnError
 public void onError(Session session, Throwable throwable, @PathParam("userid") String userid) {

 }

 /**
  * 服务端推送消息
  *
  * @param session
  * @param message
  * @param userid
  */

 public static void sendMessageFromServer(Session session,String message,String userid){

  try{
   //异步通知
//   session.getAsyncRemote ().setSendTimeout (10000);
//   session.getAsyncRemote ().sendText ( message );
   //同步
  session.getBasicRemote().sendText(message);

  }catch (Exception e){
   e.printStackTrace ();
  }
 }
}

3.Controller 端

@Controller
@RequestMapping(value = "/websocket")
@Slf4j
public class WebSocketController {

    // 跳转测试路径
    @GetMapping("testwebSocket.html")
    public String testwebSocket() {
        return "testwocket";
    }

    //服务端去客户端发送消息  发送消息接口
    @GetMapping("fdkSendMsg.json")
    public void fdkSendMsg() {
        //用户id  作为key  session 作为value;
        System.out.println("===========发送消息==============");
        System.out.println(WebSocketServer.mapsession.size());
        Session session = (Session) WebSocketServer.mapsession.get("1");
        if (session != null) {
            WebSocketServer.sendMessageFromServer(session, "Yes", "1");
        }

    }
}

4.页面Js

 WebSocketTest();
    function WebSocketTest()
    {
        if ("WebSocket" in window)
        {
            alert("您的浏览器支持 WebSocket!");
                var id =1;
            // 打开一个 web socket      
            var ws = new WebSocket("ws://localhost:8081/webSecketTest/sendMsg/"+id);
    
            ws.onopen = function()
            {
                // Web Socket 已连接上,使用 send() 方法发送数据
                // ws.send("发送数据");
                alert("连接成功...");
            };

            ws.onmessage = function (evt)
            {
                var msg = evt.data;
                alert(msg);
                //判断是否需要更新
                if(msg=="Yes"){
                    //更新
                }
            };
            ws.onclose = function()
            {
                // 关闭 websocket
                alert("连接已关闭...");
            };
        }

        else
        {
            // 浏览器不支持 WebSocket
            alert("您的浏览器不支持 WebSocket!");
        }
    }

你可能感兴趣的:(websocket)