• Java Springboot webSocket简单实现,调接口推送消息到客户端socket


    Java Springboot webSocket简单实现,调接口推送消息到客户端socket

    后台一般作为webSocket服务器,前台作为client。真实场景可能是后台程序在运行时(满足一定条件时),去给client发数据。

    再补充一个SpringBoot的client吧

    1、依赖

            <dependency>
                <groupId>org.java-websocket</groupId>
                <artifactId>Java-WebSocket</artifactId>
                <version>1.5.2</version>
            </dependency>

    2、client代码

    package com.aircas.satellitemanagement.socket.client;
    
    import org.java_websocket.client.WebSocketClient;
    import org.java_websocket.handshake.ServerHandshake;
    
    import java.net.URI;
    
    public class WsClient extends WebSocketClient {
    
        public WsClient(URI serverUri) {
            super(serverUri);
        }
    
        @Override
        public void onOpen(ServerHandshake arg0) {
            System.out.println("握手成功");
    
        }
    
        @Override
        public void onClose(int arg0, String arg1, boolean arg2) {
            System.out.println("连接关闭");
        }
    
        @Override
        public void onError(Exception arg0) {
            System.out.println("发生错误");
        }
    
        @Override
        public void onMessage(String arg0) {
            System.out.println("收到消息" + arg0);
        }
    }
    package com.aircas.satellitemanagement.socket.client;
    
    import org.java_websocket.enums.ReadyState;
    
    import java.net.URI;
    
    public class Client {
        // 根据实际websocket地址更改
        private static String url = "ws://localhost:9101/webSocket/TT";
    
        public static void main(String[] args) {
            try {
                WsClient myClient = new WsClient(new URI(url));
                myClient.connect();
                // 判断是否连接成功,未成功后面发送消息时会报错
                while (!myClient.getReadyState().equals(ReadyState.OPEN)) {
                    System.out.println("连接中···请稍后");
                    Thread.sleep(1000);
                }
                myClient.send("MyClient");
                System.out.println("发送成功");
                myClient.send("test1");
                myClient.send("test2");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
  • 相关阅读:
    mongodb的学习-1-NoSQL
    mongodb的学习-3-在Mac上的安装配置
    面试题之算法与编程
    笔试题之javaweb
    笔试题之j2ee
    笔试题之代码查错
    笔试题之java基础
    javaweb笔记分享
    过滤器入门
    jsp入门
  • 原文地址:https://www.cnblogs.com/myfrank/p/14798947.html
Copyright © 2020-2023  润新知