使用IDEA 写的Spring-WebSocket Demo

使用IDEA 写的Spring-WebSocket Demo

参考 https://www.cnblogs.com/nosqlcoco/p/5860730.html

最近项目上基于spring-boot开发,用到了websocket,参考网上的资料写了个demo


新建项目

打开IDEA:
File -》New -》Project
在左侧栏里选中 Spring Initializr之后,点击next按钮,再点击next按钮,到选择Dependencies页面的Web下面选中websocket和web这两个依赖之后,点击next然后finish。
上述操作就完成了项目创建和所需要依赖包的引入了。

代码

WebSocketConfig.java
用于配置websocket相关的连接信息

package com.example.websocketdemo.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * @since 参考 https://www.cnblogs.com/nosqlcoco/p/5860730.html
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myWebSocketHandler(),"/websocket").setAllowedOrigins("*");
        registry.addHandler(myWebSocketHandler(),"/sockjs").setAllowedOrigins("*").withSockJS();
    }

    @Bean
    MyWebSocketHandler myWebSocketHandler(){
        return new MyWebSocketHandler();
    }
}

MyWebSocketHandler.java
用于处理:连接开启、连接关闭、接收消息、发送消息

package com.example.websocketdemo.websocket;

import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.util.concurrent.ConcurrentHashMap;

public class MyWebSocketHandler extends TextWebSocketHandler {

    private static ConcurrentHashMap<String,WebSocketSession> clientMap = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        clientMap.put(session.getId(),session);
        super.afterConnectionEstablished(session);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        System.out.println(session.getId()+"||"+message.getPayload());
        super.handleMessage(session, message);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        session.sendMessage(new TextMessage(session.getId()+"||"+message.getPayload()));
        super.handleTextMessage(session, message);
    }

    @Override
    protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
        super.handlePongMessage(session, message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println(session.getId()+"is closed");
        super.afterConnectionClosed(session, status);
    }

    public static ConcurrentHashMap<String, WebSocketSession> getClientMap() {
        return clientMap;
    }

    public static void setClientMap(ConcurrentHashMap<String, WebSocketSession> clientMap) {
        MyWebSocketHandler.clientMap = clientMap;
    }
}

websocket.html
用于前端(终端)页面进行websocket连接测试

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf8">
    <title>websocket demo</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
WEBSOCKET
<hr/>
<h2>Data</h2>
<input type="text" id="input_params" value='{"id":"01"}'>

<button onclick="sendTo()">Send</button>
<button onclick="closeSocket()">CloseSocket</button>

<div id="content"><p>content</p></div>

<script>
    var sock = new SockJS('http://localhost:8080/sockjs');

    function sendTo() {
        var params = $("#input_params").val();
        console.log("params:"+params);
        sock.send(params);
        $("#content").after($("<span>send</span><br/>"));
    }

    function closeSocket() {
        console.log("close socket")
        sock.close();
    }

    sock.onopen = function() {
        console.log('open');
        sock.send("Hi");
    };

    sock.onmessage = function(e) {
        console.log('message', e.data);
        $("#content").after(e.data);
    };

    sock.onclose = function() {
        console.log('close');
    };

</script>
</body>
</html>

pom.xml
这里给出pom.xml,方便eclipse的童鞋也能清楚需要到哪些依赖

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>websocketdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>websocketdemo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.13.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

部分知识点

通过对websocket的连接和断开测试,发现:如果客户端突然断网,服务端的websocket会过5到10秒这样关闭这个断掉的连接。会调用afterConnectionClosed()这个方法,不需要自己做心跳检测。


这里给出demo的下载地址:
https://download.csdn.net/download/u013506207/10419187

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值