項(xiàng)目中需要向頁(yè)面推送消息..決定采用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("有新客戶加入!當(dāng)前在線人數(shù) $onlineCount")
sendMsg("你好!客戶端")
try {
sendMsg("test")
} catch(e: Exception) {
println("${e.message}")
}
}
@OnClose
fun onClose() {
webSocketSet.remove(this)
subOnlineCount()
println("客戶退出!當(dāng)前在線人數(shù) $onlineCount")
}
@OnMessage
fun onMsg(msg: String, session: Session) {
println("客戶端傳來(lái)的消息:$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("有訂單導(dǎo)入!!")
}
}
到這里就可以實(shí)現(xiàn)服務(wù)器向web推送消息的方式了.