springboot使用Websocket写一个聊天室
阅读原文时间:2023年08月24日阅读:3

1
2 3 org.springframework.boot 4 spring-boot-starter-websocket 5

目录

一、WebSocketConfig配置类

1 package com.example.demo.taotao.chat.webSocket;
2
3 import org.springframework.context.annotation.Bean;
4 import org.springframework.context.annotation.Configuration;
5 import org.springframework.web.socket.server.standard.ServerEndpointExporter;
6
7 @Configuration
8 public class WebSocketConfig {
9 @Bean
10 public ServerEndpointExporter serverEndpointExporter() {
11 return new ServerEndpointExporter();
12 }
13
14 }

二、WebSocket 类

1 package com.example.demo.taotao.chat.webSocket;
2
3 import org.springframework.stereotype.Component;
4
5 import javax.websocket.OnClose;
6 import javax.websocket.OnMessage;
7 import javax.websocket.OnOpen;
8 import javax.websocket.Session;
9 import javax.websocket.server.ServerEndpoint;
10 import java.io.IOException;
11 import java.text.SimpleDateFormat;
12 import java.util.Locale;
13 import java.util.concurrent.CopyOnWriteArraySet;
14
15 @Component
16 @ServerEndpoint("/webSocket")
17 @SuppressWarnings("all")
18 public class WebSocket {
19
20 private Session session;
21
22 private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet<>();
23
24 @OnOpen
25 public void onOpen(Session session) {
26 this.session = session;
27 webSocketSet.add(this);
28 System.out.println("新的连接 总数:" + webSocketSet.size());
29 sendMessage("聊天室新来人了 总数:" + webSocketSet.size());
30 sendMessage("");
31
32 }
33
34
35 @OnClose
36 public void onColse() {
37 webSocketSet.remove(this);
38 System.out.println("断开连接 总数:" + webSocketSet.size());
39
40 }
41
42 /**
43 * 接收客户端发来的消息
44 *
45 * @param message
46 * @param name
47 */
48 @OnMessage
49 public void onMessage(String message) {
50 System.out.println("收到客户端发来的消息:");
51 //接到客户端的消息后将消息推送给所有人
52 SimpleDateFormat sdf1 = new SimpleDateFormat("", Locale.SIMPLIFIED_CHINESE);
53 sdf1.applyPattern("yyyy-MM-dd HH:mm:ss");
54
55 sendMessage(sdf1.format(System.currentTimeMillis()) + "\n");
56 sendMessage(message);
57 sendMessage("");
58 }
59
60 /**
61 * 向客户端发送消息的方法
62 *
63 * @param message
64 */
65 public void sendMessage(String message) {
66 for (WebSocket webSocket : webSocketSet) {
67 System.out.println("广播消息:" + message);
68 try {
69 webSocket.session.getBasicRemote().sendText(message);
70 } catch (IOException e) {
71 e.printStackTrace();
72 }
73
74 }
75 }
76 }

三、前端(HTML)

1
2 3 4 My WebSocket 5 6 7 8 welcome chat
9 10 12

13
14 15 16 68

运行

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器