websocket

項目中需要向頁面推送消息..決定采用websocket

部分代碼copy網(wǎng)上的

config: websocket的配置

@Configuration
@EnableWebSocket
open class WebSocketConfig : WebSocketConfigurer {
    override fun registerWebSocketHandlers(p0: WebSocketHandlerRegistry?) {
        p0?.addHandler(MyWebSocketHander(),"/test")?.addInterceptors(MyHandshakeInterceptor())
    }
    @Bean open fun serverEndpointExporter() : ServerEndpointExporter {
        return ServerEndpointExporter()
    }
}

socketHandler類

  @ServerEndpoint("/test")
  @Component
  class MyWebSocket {
      companion object {
          val webSocketSet = CopyOnWriteArraySet<MyWebSocket>()
          var onlineCount = 0
      }
    var session: Session? = null
    @OnOpen
    fun onOpen(session: Session) {
        this.session = session
        webSocketSet.add(this)
        addOnlineCount()
        println("有新客戶加入!當前在線人數(shù) $onlineCount")
        sendMsg("你好!客戶端")
        try {
            sendMsg("test")
        } catch(e: Exception) {
            println("${e.message}")
        }
    }
    @OnClose
    fun onClose() {
        webSocketSet.remove(this)
        subOnlineCount()
        println("客戶退出!當前在線人數(shù) $onlineCount")
    }
    @OnMessage
    fun onMsg(msg: String, session: Session) {
        println("客戶端傳來的消息:$msg")
        for (item in webSocketSet) {
            item.sendMsg("msg:$msg")
        }
    }
    fun subOnlineCount() {
        onlineCount--
    }
    fun addOnlineCount(): Int {
        return onlineCount++
    }
    fun sendMsg(msg: String) {
        this.session?.basicRemote?.sendText(msg)
    }
}

最后就是控制類

@PostMapping("xxxx")
@MessageMapping("/test")
    fun test(){
      val webSocketSet = MyWebSocket.webSocketSet
            for (item in webSocketSet) {
                   item.sendMsg("有訂單導入!!")
                }
      }

到這里就可以實現(xiàn)服務器向web推送消息的方式了.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容