人生到头来,就是不断放下,但永远最令人心|

durtime

园龄:4年7个月粉丝:10关注:1

springboot使用websocket

WebSocket概念

WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端。

WebSocket通信协议于2011年被IETF定为标准RFC 6455,并被RFC7936所补充规范。

和http协议不同的就是一种长连接,http是无状态的连接,当请求回复后就会断开连接,是阻塞式连接,当服务端一直在处理时,客户端是接受

不到回复的,就会一直等待,发生阻塞,直到有回复。服务端不能主动联系客户端,只能客户端发起。

而WebSocket协议则是一种持久化通信协议,在第一次发起http请求后,请求头携带有关的WebSocket参数,服务器进行协议升级,HTTP->Websocket

建立持久连接,服务端会一直知道连接信息,直到客户端关闭请求。不用再多次发送http请求并且解析。

应用场景:如需要不断获取最新消息或数据,要求实时性的应用,此时就可以使用websocket来建立链接,解决数据传输。

使用 方法1

1
2
3
4
5
6
//springboot内置tomcat<br>//添加依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>2.5.6</version>
        </dependency>

 

注入ServerEndpointExporte

 

1
2
3
4
5
6
7
8
@Configuration
public class SocketConfig{<em id="__mceDel">//自动注册使用了@ServerEndpoint注解声明的对象
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
</em>

 websocket的具体实现类

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
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
 <br>//将目前的类定义成一个websocket服务器端,通过注解设置的url值来连接
@ServerEndpoint(value = "/client")
@Component
public class PushSocket {
     
    private static Logger logger = LogManager.getLogger(PushSocket.class.getName());
     
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
       
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<PushSocket> wsClientMap = new CopyOnWriteArraySet<>(); 
   
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
     
    /**
     * 连接建立成功调用的方法
     * @param session 当前会话session
     */
    @OnOpen
    public void onOpen (Session session){
        this.session = session;
        wsClientMap.add(this);
        addOnlineCount();
        logger.info(session.getId()+"有新链接加入,当前链接数为:" + wsClientMap.size());
    }
   
    /**
     * 连接关闭
     */
    @OnClose
    public void onClose (){
        wsClientMap.remove(this); 
        subOnlineCount(); 
        logger.info("有一链接关闭,当前链接数为:" + wsClientMap.size());
    }
   
    /**
     * 收到客户端消息
     * @param message 客户端发送过来的消息
     * @param session 当前会话session
     * @throws IOException
     */
    @OnMessage
    public void onMessage (String message, Session session) throws IOException {
        logger.info("来终端的警情消息:" + message);
        sendMsgToAll(message);
    }
     
    /**
     * 发生错误
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.info("wsClientMap发生错误!");
        error.printStackTrace();
    }
     
    /**
     * 给所有客户端群发消息
     * @param message 消息内容
     * @throws IOException
     */
    public void sendMsgToAll(String message) throws IOException {
        for ( WarningPushSocket item : wsClientMap ){ 
            item.session.getBasicRemote().sendText(message);
        }
        logger.info("成功群送一条消息:" + wsClientMap.size());
    }
   
    public void sendMessage (String message) throws IOException {
        this.session.getBasicRemote().sendText(message); 
        logger.info("成功发送一条消息:" + message);
    }
   
    public static synchronized  int getOnlineCount (){
        return WarningPushSocket.onlineCount; 
    }
   
    public static synchronized void addOnlineCount (){
        WarningPushSocket.onlineCount++; 
    }
   
    public static synchronized void subOnlineCount (){
        WarningPushSocket.onlineCount--; 
    }
}

  

html

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
<!DOCTYPE HTML>
<html>
<head>
    <title>My WebSocket</title>
</head>
  
  
<body>
Welcome<br/>
<input id="text" type="text" /><button οnclick="send()">Send</button>    <button οnclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
  
  
<script type="text/javascript">
    var websocket = null;
  
    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        websocket = new WebSocket("ws://localhost:8080/client");
    }
    else{
        alert('Not support websocket')
    }
  
  
    //连接发生错误的回调方法
    websocket.onerror = function(){
        setMessageInnerHTML("error");
    };
  
  
    //连接成功建立的回调方法
    websocket.onopen = function(event){
        setMessageInnerHTML("open");
    }
  
  
    //接收到消息的回调方法
    websocket.onmessage = function(event){
        setMessageInnerHTML(event.data);
    }
  
  
    //连接关闭的回调方法
    websocket.onclose = function(){
        setMessageInnerHTML("close");
    }
  
  
    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function(){
        websocket.close();
    }
  
  
    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }
  
  
    //关闭连接
    function closeWebSocket(){
        websocket.close();
    }
  
  
    //发送消息
    function send(){
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>

  

方法2

使用spring-boot-starter-websocket的推荐方法

添加配置

1
2
3
4
5
6
7
8
9
10
@Configuration
@EnableWebSocket
public class SocketConfig2 implements WebSocketConfigurer {//实现接口
 
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new MyWebSocketHandler(), "/client")//设置连接路径和处理
                .setAllowedOrigins("*");
    }
}

  

添加处理器

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
import org.springframework.web.socket.*;
 
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
public class MyWebSocketHandler implements WebSocketHandler {//实现接口
    private static final Map<String, WebSocketSession> SESSIONS = new ConcurrentHashMap<>();
 
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String userName = "test";
        SESSIONS.put(userName, session);
        System.out.println(String.format("成功建立连接~ userName: %s", userName));
    }
 
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        String msg = message.getPayload().toString();
        System.out.println(msg);
    }
 
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("连接出错");
        if (session.isOpen()) {
            session.close();
        }
    }
 
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        System.out.println("连接已关闭,status:" + closeStatus);
    }
 
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
 
    /**
     * 发消息
     * @param userName
     * @param message
     */
    public static void sendMessage(String userName, String message) {
        WebSocketSession webSocketSession = SESSIONS.get(userName);
        if (webSocketSession == null || !webSocketSession.isOpen()) return;
        try {
            webSocketSession.sendMessage(new TextMessage(message));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
 
    /**
     * 群发消息
     * @param message
     */
    public static void sendMessageAll(String message) {
        SESSIONS.keySet().forEach(us -> sendMessage(us, message));
    }
}

  

本文作者:durtime

本文链接:https://www.cnblogs.com/durtime/p/16267010.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   durtime  阅读(221)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
历史上的今天:
2021-05-13 05程序员修炼之道:从小工到专家阅读笔记之二
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
展开