引入依赖
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
|
配置
1 2 3 4 5 6 7 8 9 10
| @Configuration public class TestConfig {
@Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
|
服务端
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
| @Component @ServerEndpoint("/ws/{uid}") public class WebSocket {
static final Map<String, Session> map = new HashMap<>();
@OnOpen public void onOpen(Session session, @PathParam("uid") String uid) { System.out.println("新客户端连接:" + uid); map.put(uid, session); }
@OnMessage public void onMessage(String message, @PathParam("uid") String uid) throws IOException { System.out.println("收到来自客户端:" + uid + "的信息:" + message); JSONObject json = JSON.parseObject(message); String to = json.getString("to"); String msg = json.getString("msg"); Session session = map.get(to); if (session != null && msg != null) { session.getBasicRemote().sendText(msg); } }
@OnClose public void onClose(@PathParam("uid") String uid) { System.out.println("连接关闭:" + uid); map.remove(uid); } }
|
客户端
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
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> let websocket = new WebSocket("ws://localhost:8080/ws/1"); websocket.onopen = function () { console.log("连接"); } websocket.onmessage = function (event) { console.log(event.data); document.getElementById("receive").innerHTML += "<p>" + event.data + "</p>"; } websocket.onclose = function () { console.log("关闭"); } function send() { let to = document.getElementById("to").value; let msg = document.getElementById("msg").value; let data = {to: to, msg: msg}; let dataStr = JSON.stringify(data); websocket.send(dataStr); } </script> </head> <body> <input id="to"/> <input id="msg"/> <button id="btn" onclick="send()">发送</button> <p id="receive"></p> </body> </html>
|
启动两个客户端,在连接时输入不同的uid即可。ws://localhost:8080/ws/{uid}