使用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 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 getClientMap() {
        return clientMap;
    }

    public static void setClientMap(ConcurrentHashMap clientMap) {
        MyWebSocketHandler.clientMap = clientMap;
    }
}

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


<html>
<head>
    <meta charset="utf8">
    <title>websocket demotitle>
    <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>Datah2>
<input type="text" id="input_params" value='{"id":"01"}'>

<button onclick="sendTo()">Sendbutton>
<button onclick="closeSocket()">CloseSocketbutton>

<div id="content"><p>contentp>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($("send
"
)); } 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的童鞋也能清楚需要到哪些依赖

    
<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.0modelVersion>

    <groupId>com.examplegroupId>
    <artifactId>websocketdemoartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <packaging>jarpackaging>

    <name>websocketdemoname>
    <description>Demo project for Spring Bootdescription>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>1.5.13.RELEASEversion>
        <relativePath/> 
    parent>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-websocketartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

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


project>

部分知识点

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


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

你可能感兴趣的:(web,spring-boot,websocket,idea)