SpringBoot集成websocket(1)|(websocket客户端实现)

SpringBoot集成websocket(1)|(websocket客户端实现)


章节

前言

WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

一、websocket客户端依赖引入

pom依赖如下

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

二、websocket代码实现

1.WSClient客户端实现

可以定义了websocket的client类,其他地方如果需要使用ws连接,直接注入即可使用

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.stereotype.Component;

import java.net.URI;
@Slf4j
@Component
public class WSClient {
    
    

    public WebSocketClient webSocketClient(String url) {
    
    
        try {
    
    
            WebSocketClient webSocketClient = new WebSocketClient(new URI(url),new Draft_6455()) {
    
    
                @Override
                public void onOpen(ServerHandshake handshakedata) {
    
    
                    log.info("[websocket] 连接成功");
                }

                @Override
                public void onMessage(String message) {
    
    
                    log.info("[websocket] 收到消息={}",message);

                }
                @Override
                public void onClose(int code, String reason, boolean remote) {
    
    
                    log.info("[websocket] 退出连接");
                }

                @Override
                public void onError(Exception ex) {
    
    
                    log.info("[websocket] 连接错误={}",ex.getMessage());
                }
            };
            webSocketClient.connect();
            return webSocketClient;
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return null;
    }
}

2.WSClient客户端使用实例

定义了怎么使用WSClient类建立一个ws连接

@Api(tags = {
    
    "websocket测试"})
@RestController
@RequestMapping("/ws")
public class SendMessageCtrl {
    
    


    @Autowired
    private WSClient wsClient;

    @GetMapping(value = "hello")
    public void hello(String name) throws InterruptedException {
    
    
        WebSocketClient client = this.wsClient.webSocketClient("ws://localhost:8905/ws/test");
        if (client != null){
    
    
            for (int i = 0; i < 10; i++) {
    
    
                Thread.sleep(1000);
                client.send("客户端发送消息"+i);
            }
        }
    }
}

三、实际使用场景

1.多WSClient连接使用

上述是一个简单的demo,能够通过客户端连接websocket接口,但实际场景可能是很多用户访问本地的服务,改服务需要调用远程的ws接口,这个时候怎么区分用户间独立的建立websocket连接呢

思路:定义一个全局变量,用于存放websocket的客户端,客户端触发发送消息事件,在全局变量里面获取对应的client进行消息发送

@Api(tags = {
    
    "websocket测试"})
@RestController
@RequestMapping("/ws")
public class SendMessageCtrl {
    
    


    @Autowired
    private WSClient wsClient;

    private static ConcurrentHashMap<String, WebSocketClient> wsClientSet = new ConcurrentHashMap<>();


    @GetMapping(value = "hello")
    public void hello(String name) {
    
    
        WebSocketClient client;
        if (wsClientSet.containsKey(name)) {
    
    
            client = wsClientSet.get(name);
        } else {
    
    
            client = this.wsClient.webSocketClient("ws://localhost:8905/ws/" + name);
            wsClientSet.put(name, client);
        }
        if (client != null) {
    
    
            client.send("请根据卖火柴的小女孩生成一个类似的故事");
        }
    }
}

总结

以上就是SpringBoot集成websocket客户端的内容,用于后端服务调用websocket请求。具体业务逻辑执行在代码中自己实现,这里只是给了具体的demo和实例,实际中运用场景还需要自己琢磨。

猜你喜欢

转载自blog.csdn.net/Oaklkm/article/details/130705555