• SpringBoot之WebSocket服务搭建


    SpringBoot之WebSocket服务搭建

    WebSockets 彻底改变了 Web,将笨拙、缓慢的实时交互转变为时尚、低延迟的体验,使其成为动态、用户友好型应用程序的首选。

    1.创建SpringBoot工程

    在Intellij IDEA工具中使用SpringBoot项目初始化向导新建一个工程,如工程名为yuan-websocket-demo

    2. pom.xml中引入依赖

    
    <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">
        <parent>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-parentartifactId>
            <version>2.3.0.RELEASEversion>
        parent>
        <modelVersion>4.0.0modelVersion>
    
        <artifactId>yuan-websocket-demoartifactId>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-websocketartifactId>
            dependency>
    
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-thymeleafartifactId>
            dependency>
           
            
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>fastjsonartifactId>
                <version>1.2.68version>
            dependency>
    
        dependencies>
    
    project>
    
    • 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

    3. application.yml配置

    server:
      port: 2001
      max-http-header-size: 8192
    spring:
      thymeleaf:
        cache: false
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    4. 主启动类

    主启动类中标注开启WebSoket的注解@EnableWebSocket

    package org.yuan;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.web.servlet.ServletComponentScan;
    import org.springframework.web.socket.config.annotation.EnableWebSocket;
    
    /**
     * 

    * Description:
    *

    * Author:jinshengyuan
    * Datetime: 2020-05-29 15:00 *

    * */
    @SpringBootApplication @EnableWebSocket @ServletComponentScan public class MyWebSocketApplication { public static void main(String[] args) { SpringApplication.run(MyWebSocketApplication.class, args); } }
    • 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

    5. 编写MyWebSocket服务类

    package org.yuan.mysoket;
    
    import org.springframework.stereotype.Component;
    
    import javax.websocket.*;
    import javax.websocket.server.ServerEndpoint;
    import java.io.IOException;
    import java.util.concurrent.CopyOnWriteArraySet;
    @Component
    @ServerEndpoint("/myChat")
    public class MyWebSocket {
        private static int onLineCount = 0;//记录在线连接数,应该做成线程安全的
    
        //线程安全set,用来存储每个客户的MyWebSocket对象
        private static CopyOnWriteArraySet<MyWebSocket> myWebSockets = new CopyOnWriteArraySet<>();
    
        //与某个客户端的连接会话,需要通过它来给客户发送数据
        private Session session;
    
        /**
         * 

    * Description: 连接建立成功后调用的方法
    *

    * Author:jinshengyuan
    * Datetime: 2020/5/28 22:25 *

    * * @return * @since 2020/5/28 22:25 */
    @OnOpen public void onOpen(Session session) { System.out.println("连接了哦"); this.session = session; myWebSockets.add(this); addOnlineCount(); System.out.println(); } /** *

    * Description: 关闭会话连接
    *

    * Author:jinshengyuan
    * Datetime: 2020/5/28 22:39 *

    * * @param * @param * @return * @since 2020/5/28 22:39 */
    @OnClose public void onClose(Session session) { myWebSockets.remove(this); subOnlineCount(); } /** *

    * Description: 发送消息
    *

    * Author:jinshengyuan
    * Datetime: 2020/5/28 22:39 *

    * @since 2020/5/28 22:39 */
    @OnMessage public void onMessage(String message, Session session) { System.out.println("来自客户端的消息:" + message); for (MyWebSocket socket : myWebSockets) { try { socket.sendMessage(message); } catch (IOException e) { e.printStackTrace(); continue; } } } public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } @OnError public void onError(Session session, Throwable error) { System.out.println("发送消息失败"); error.printStackTrace(); } public static synchronized void addOnlineCount() { MyWebSocket.onLineCount++; } public static synchronized void subOnlineCount() { MyWebSocket.onLineCount--; } public static synchronized int getOnLineCount() { return onLineCount; } }
    • 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
    • 101
    • 102
    • 103
    • 104
    • 105

    6. 编写测试页面

    index.html如下

    
    
    <html><head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <title>web_sockettitle>
      <script type="text/javascript">
        var ws;
        
        function init() {
    
          // Connect to Web Socket.
          // Change host/port here to your own Web Socket server.
          ws = new WebSocket("ws://localhost:2001/myChat");
    
          // Set event handlers.
          ws.onopen = function() {
            output("onopen");
          };
          ws.onmessage = function(e) {
            // e.data contains received string.
            output("onmessage: " + e.data);
          };
          ws.onclose = function() {
            output("onclose");
          };
          ws.onerror = function() {
            output("onerror");
          };
        }
        
        function onSubmit() {
          var input = document.getElementById("input");
          // You can send message to the Web Socket using ws.send.
          ws.send(input.value);
          output("send: " + input.value);
          input.value = "";
          input.focus();
        }
        
        function onCloseClick() {
          ws.close();
        }
        
        function output(str) {
          var log = document.getElementById("log");
          var escaped = str.replace(/&/, "&").replace(/</, "<").
            replace(/>/, ">").replace(/"/, """); // "
          log.innerHTML = escaped + "
    "
    + log.innerHTML; }
    script> head> <body onload="init();"> <form onsubmit="onSubmit(); return false;"> <input type="text" id="input"> <input type="submit" value="Send"> <button onclick="onCloseClick(); return false;">closebutton> form> <div id="log">div> body>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

    启动SpringBoot应用后,浏览器中输入地址进行测试:http://localhost:2001

  • 相关阅读:
    2流高手速成记(之六):从SpringBoot到SpringCloudAlibaba
    翻页-时钟
    python yield用法
    系统架构师笔记——嵌入式系统
    制作一个模板
    【日志采集系统】python实现-附ChatGPT解析
    国产开发板——香橙派Kunpeng Pro的上手初体验
    Mobpush上线跨时区推送功能,助力中国开发者应用出海
    基于PHP+html+MySQL的团购商城电商平台设计
    Linux学习--MySQL学习之查询语句
  • 原文地址:https://blog.csdn.net/yuanjinshenglife/article/details/136267421