SpringBoot 整合websocket客户端代码写法示例

Posted 洛阳泰山

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot 整合websocket客户端代码写法示例相关的知识,希望对你有一定的参考价值。

pom文件需要引入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                    <groupId>org.springframework.boot</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>

代码如下:


import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.utils.DateUtil;

import javax.websocket.*;
import java.net.URI;

@ClientEndpoint
@Slf4j
public class WSClient 

    private Session session;

    @OnOpen
    public void open(Session session) 
        log.info("Client WebSocket is opening...");
        this.session = session;
    

    @OnMessage
    public void onMessage(String message) 
        log.info("时间: " + DateUtil.time());
        log.info("Server send message: " + message);
    

    @OnClose
    public void onClose() 
        log.info("Websocket closed");
    

    /**
     * 发送客户端消息到服务端
     *
     * @param message 消息内容
     */
    public void send(String message) 
        this.session.getAsyncRemote().sendText(message);
    

    public static void main(String[] args) 
        try 
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            WSClient client = new WSClient();
            container.connectToServer(client, new URI("ws://172.16.10.203:12000/ws/automate"));
            container.setDefaultMaxSessionIdleTimeout(5000L);
            client.send("inertial_navigation_data");
            Thread.sleep(600000);
        catch (Exception e)
            e.printStackTrace();
        
    

idea里右键运行主方法

控制台输出结果如下

 

以上是关于SpringBoot 整合websocket客户端代码写法示例的主要内容,如果未能解决你的问题,请参考以下文章

Springboot整合Websocket遇到的坑

Springboot1.5.9整合WebSocket

Springboot项目整合WebSocket源码分析

SpringBoot 整合websocket客户端代码写法示例

开发经验springboot整合websocket实现群聊

springboot整合websocket实现客户端与服务端通信