项目中需要向页面推送消息..决定采用websocket
部分代码copy网上的
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("有新客户加入!当前在线人数 $onlineCount")
sendMsg("你好!客户端")
try {
sendMsg("test")
} catch(e: Exception) {
println("${e.message}")
}
}
@OnClose
fun onClose() {
webSocketSet.remove(this)
subOnlineCount()
println("客户退出!当前在线人数 $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("有订单导入!!")
}
}
到这里就可以实现服务器向web推送消息的方式了.