1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
| package top.zfxt.chat.service
import cn.hutool.json.JSONArray import cn.hutool.json.JSONObject import cn.hutool.json.JSONUtil import jakarta.websocket.* import jakarta.websocket.server.PathParam import jakarta.websocket.server.ServerEndpoint import org.slf4j.LoggerFactory import org.springframework.stereotype.Controller import org.springframework.stereotype.Service import top.zfxt.chat.pojo.User import java.nio.ByteBuffer import java.util.* import java.util.concurrent.ConcurrentHashMap
@Service @ServerEndpoint("/chat/{username}") class WebSocketServer { companion object{ val UsersMap:MutableMap<String, User?> = mutableMapOf()
val log = LoggerFactory.getLogger(WebSocketServer.javaClass)
val sessionMap:MutableMap<String,Session> = ConcurrentHashMap(); }
@OnOpen public fun onOpen(session:Session,@PathParam("username") username:String){ var newUser: User? = UsersMap.get(username) newUser?.status = "online" if(newUser==null) { var userId = UUID.randomUUID().toString().replace("-","").substring(0,10) newUser = User(userId,username,null,"online")
}
UsersMap.put(username,newUser) sessionMap.put(username,session) log.info("有新用户加入,username={},当前在线人数为:{}",username, sessionMap.size)
var systemMessage = JSONObject().set("isSystem",true).set("users", UsersMap.values) sendAllMessage(JSONUtil.toJsonStr(systemMessage))
}
@OnClose public fun onClose(session: Session,@PathParam("username") username: String){ sessionMap.remove(username) UsersMap.remove(username) log.info("有一连接关闭,移除username={}的用户session,当前在线人数为:{}",username, sessionMap.size) var systemMessage = JSONObject().set("isSystem",true).set("users", UsersMap.values) sendAllMessage(JSONUtil.toJsonStr(systemMessage)) }
@OnMessage(maxMessageSize = 1024*1024*10) public fun onMessage(message: String,@PathParam("username") username: String){ log.info("服务器收到用户username={}的消息:{}",username,message) var obj = JSONUtil.parseObj(message) var fromname = obj.getStr("from") var toUsername = obj.getStr("to") var toSession = sessionMap.get(toUsername) if(toSession != null){ var message = JSONObject().set("isSystem",false).set("message",obj).toString() sendMassage(message,toSession) log.info("用户{}发送给用户username={},消息:{}",fromname,toUsername,message) }else{ log.info("发送失败,未找到用户username={}的session",toUsername) UsersMap.remove(toUsername) } } @OnError public fun onError(session: Session,error:Throwable){ log.error("发生错误") error.printStackTrace() }
private fun sendMassage(message:String,toSession: Session){ try { log.info("服务器给客户端[{}]发送消息{}",toSession.id,message) toSession.basicRemote.sendText(message) }catch (e:Exception){ log.error("服务器发送消息给客户端失败",e) } }
private fun sendImage(image:ByteBuffer,toSession: Session){ toSession.basicRemote.sendBinary(image) }
private fun sendAllMessage(message:String){ try { for(session in sessionMap.values){ log.info("服务端给客户端[{}]发送消息{}",session.id,message) session.basicRemote.sendText(message) } }catch (e:Exception){ log.error("服务器发送消息给客户端失败",e) } } }
|