• websocket学习


    写在前面

    新公司用到了websocket技术,所以这里学习下。

    1:Java原生

    1.1:maven

    <dependency>
        <groupId>org.java-websocketgroupId>
        <artifactId>Java-WebSocketartifactId>
        <version>1.5.3version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    1.2:server

    public class SocketServer extends WebSocketServer {
    
        public SocketServer(int port) throws UnknownHostException {
            super(new InetSocketAddress(port));
        }
    
        public SocketServer(InetSocketAddress address) {
            super(address);
        }
    
        @Override
        public void onOpen(WebSocket conn, ClientHandshake handshake) {
            conn.send("Welcome to the server!"); // This method sends a message to the new client
            broadcast("new connection: " + handshake
                    .getResourceDescriptor()); // This method sends a message to all clients connected
            System.out.println(
                    conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!");
        }
    
        @Override
        public void onClose(WebSocket conn, int code, String reason, boolean remote) {
            broadcast(conn + " has left the room!");
            System.out.println(conn + " has left the room!");
        }
    
        @Override
        public void onMessage(WebSocket conn, String message) {
            broadcast(message + "by server");
            System.out.println(conn + ": " + message);
        }
    
        @Override
        public void onError(WebSocket conn, Exception ex) {
            ex.printStackTrace();
            if (conn != null) {
                // some errors like port binding failed may not be assignable to a specific
                // websocket
            }
        }
    
        @Override
        public void onStart() {
            System.out.println("Server started!");
            setConnectionLostTimeout(0);
            setConnectionLostTimeout(100);
        }
    }
    
    • 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

    1.3:main

    public class MyMain {
        public static void main(String[] args) throws InterruptedException, IOException {
            int port = 8887; // 843 flash policy port
            SocketServer s = new SocketServer(port);
            s.start();
            System.out.println("ChatServer started on port: " + s.getPort());
    
            BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String in = sysin.readLine();
                s.broadcast(in);
                if (in.equals("exit")) {
                    s.stop(1000);
                    break;
                }
            }
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    启动:

    SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
    ChatServer started on port: 8887
    Server started!
    
    • 1
    • 2
    • 3

    1.4:测试

    我们使用如下的工具 来测试:
    在这里插入图片描述

    在地址框录入地址ws://localhost:8887,测试如下:
    在这里插入图片描述

    可以再调试工具查看交互的过程:
    在这里插入图片描述

    2:java原生+springboot

    2.1:pom

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-dependenciesartifactId>
                <version>2.7.7version>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-websocketartifactId>
        dependency>
    dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    2.2:程序

    • 定义连接端点endpoint
    @ServerEndpoint("/myWs")
    @Component
    public class WsServerEndpoint {
    
        /**
         * 连接成功
         *
         * @param session
         */
        @OnOpen
        public void onOpen(Session session) {
            System.out.println("连接成功");
        }
    
        /**
         * 连接关闭
         *
         * @param session
         */
        @OnClose
        public void onClose(Session session) {
            System.out.println("连接关闭");
        }
    
        /**
         * 接收到消息
         *
         * @param text
         */
        @OnMessage
        public String onMsg(String text) throws IOException {
            return "servet 发送:" + text;
        }
    }
    
    • 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
    • 暴漏服务
    @Configuration
    @EnableWebSocket
    public class WebsocketConfig {
    
        @Bean
        public ServerEndpointExporter serverEndpoint() {
            return new ServerEndpointExporter();
        } 
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • main
    @SpringBootApplication
    public class App {
    
        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    启动:

    ...
      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::                (v2.7.7)
    
    2023-11-17 11:26:14.827  INFO 24100 --- [           main] a.b.App                                  : Starting App using Java 1.8.0_202 on DESKTOP-C3DTETT with PID 24100 (E:\workspace-idea\dongshidaddy-labs-new\javabase\websocket\java_origin_and_boot\target\classes started by dell9020 in E:\workspace-idea\dongshidaddy-labs-new)
    2023-11-17 11:26:14.891  INFO 24100 --- [           main] a.b.App                                  : No active profile set, falling back to 1 default profile: "default"
    ...
    2023-11-17 11:26:50.299  INFO 24100 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 测试
      在这里插入图片描述

    写在后面

    参考文章列表

    java实现websocket的五种方式

  • 相关阅读:
    【SwiftUI模块】0060、SwiftUI基于Firebase搭建一个类似InstagramApp 2/7部分-搭建TabBar
    [Spring笔记] Spring-35-AOP通知获取数据
    【Websocket 第二篇】问题解惑
    Docker学习(5)—— 在Docker上安装软件
    点云梯度下采样
    1990-2022上市公司董监高学历工资特征信息数据/上市公司高管信息数据
    Spring 常见问题
    【广州华锐互动】VR党建多媒体互动展厅:随时随地开展党史教育
    Mysql面试笔记汇总——索引结构基础篇
    Nginx是怎么接入HTTP请求的?
  • 原文地址:https://blog.csdn.net/wang0907/article/details/134456161