springboot使用Websocket写一个聊天室

 

1         <!--websocket 依赖-->
2         <dependency>
3             <groupId>org.springframework.boot</groupId>
4             <artifactId>spring-boot-starter-websocket</artifactId>
5         </dependency>

目录

 一、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<WebSocket> 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 <!DOCTYPE HTML>
 2 <html>
 3     <head>
 4         <title>My WebSocket</title>
 5     </head>
 6 
 7     <body>
 8         welcome chat<br />
 9 
10         <input id="text" type="text" /><button onclick="send()">Send</button> <button
11             onclick="closeWebSocket()">Close</button>
12         <div id="message">
13         </div>
14     </body>
15 
16     <script type="text/javascript">
17         var websocket = null;
18         var name = "张三";
19 
20         //判断当前浏览器是否支持WebSocket
21         if ('WebSocket' in window) {
22             websocket = new WebSocket("ws://127.0.0.1:8080/webSocket");
23         } else {
24             alert('Not support websocket')
25         }
26 
27         //连接发生错误的回调方法
28         websocket.onerror = function() {
29             setMessageInnerHTML("error");
30         };
31 
32         //连接成功建立的回调方法
33         websocket.onopen = function(event) {
34             setMessageInnerHTML("连接成功");
35         }
36 
37         //接收到消息的回调方法
38         websocket.onmessage = function(event) {
39             setMessageInnerHTML(event.data);
40         }
41 
42         //连接关闭的回调方法
43         websocket.onclose = function() {
44             setMessageInnerHTML("close");
45         }
46 
47         //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
48         window.onbeforeunload = function() {
49             websocket.close();
50         }
51 
52         //将消息显示在网页上
53         function setMessageInnerHTML(innerHTML) {
54             document.getElementById('message').innerHTML += innerHTML + '<br/>';
55         }
56 
57         //关闭连接
58         function closeWebSocket() {
59             websocket.close();
60         }
61 
62         //发送消息
63         function send() {
64             var message = document.getElementById('text').value;
65             websocket.send(message);
66         }
67     </script>
68 </html>

运行

 

posted @ 2023-06-24 16:14  勤快的懒羊羊  阅读(130)  评论(0编辑  收藏  举报