SpringBoot 创建webSocket服务端

我们已经有了 HTTP 协议,为什么还需要webSocket?它能带来什么好处?
答案很简单,因为 HTTP 协议有一个缺陷:通信只能由客户端发起。
举例来说,我们想了解今天的天气,只能是客户端向服务器发出请求,服务器返回查询结果。HTTP 协议做不到服务器主动向客户端推送信息。
如果想持续从服务的获取消息,则只能使用轮询或建立长连接的方法来实现,但是这样或浪费很多不必要的资源。
而webSocket则解决了这个问题,通信可由双方发起,只需要建立一次连接,服务的端就可以持续从服务端获得消息。主要用来做消息通知,消息推送等模块

使用springBoot创建webSocket,首先要注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。要注意,如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理。

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

接着是具体实现

//用法相当于Controller localhost:8080/wensocket
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocket {
     //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
      private static int onlineCount = 0;

      //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
      private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();

      //与某个客户端的连接会话,需要通过它来给客户端发送数据
      private Session session;

      /**
       * 连接建立成功调用的方法
       * 连接时会自动调用
       */
      @OnOpen
      public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
        try {
          sendMessage("Hello world");
        } catch (IOException e) {
          System.out.println("IO异常");
        }
      }

      /**
       * 连接关闭调用的方法
       * 关闭时会自动调用
       */
      @OnClose
      public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
      }

      /**
       * 收到客户端消息后调用的方法
       *
       * @param message 客户端发送过来的消息
       * 客户端向服务端主动发送消息时调用
       */
      @OnMessage
      public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);

        //群发消息
        for (WebSocket item : webSocketSet) {
          try {
            item.sendMessage(message);
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }

      /**
       * 发生错误时调用
       */
      @OnError
      public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
      }

      //向客户端推送消息
      public void sendMessage(String message) throws IOException {
        this.session.getAsyncRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
      }


      /**
       * 群发自定义消息
       * 可以在controller中调用该方法来实时推送消息
       */
      public static void sendInfo(String message) throws IOException {
        for (WebSocket item : webSocketSet) {
          try {
            item.sendMessage(message);
          } catch (IOException e) {
            continue;
          }
        }
      }

      public static synchronized int getOnlineCount() {
        return onlineCount;
      }

      public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
      }

      public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
      }
}

现在,webSocket已经创建完毕,那我们什么时候使用呢?
可以在客户端调用某个接口时,向客户端发送某些消息,

@RestController
@RequestMapping("/hello")
public class HelloController {
    //每次调用该接口,都会发送消息
    @RequestMapping("/test1")
    public String test() throws IOException{
        //调用webSocket发送消息
        WebSocket.sendInfo("nihao");
        return "test";
    }
}

接下来,我们如何在前端使用呢?
我这里使用的是微信小程序,如果是HTML等,api略有不同

var ws = wx.connectSocket({
      url: 'ws://192.168.0.105:8080/websocket'
    });
    console.log(wx)
    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接已打开!')
    })
    wx.onSocketMessage(function (res) {
      console.log('收到服务器内容:' + res.data)
      //!!!即使跳转到其他页面,还是可以接收到服务器的信息
      //当信息服务某个条件是,触发相应事件,这个就需要自己设定了
      if (res.data == '2'){
        wx.showLoading({
          title: 'emmm',
        })
      }
    })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值