SpringBoot integrated websocket (1) | (websocket client implementation)

SpringBoot integrated websocket (1) | (websocket client implementation)


chapter

foreword

WebSocket makes the data exchange between the client and the server easier, allowing the server to actively push data to the client. In the WebSocket API, the browser and the server only need to complete a handshake, and a persistent connection can be created directly between the two, and two-way data transmission can be performed.

1. Websocket client dependency introduction

The pom depends on the following

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

Two, websocket code implementation

1. WSClient client implementation

You can define the client class of websocket. If you need to use ws connection in other places, you can use it directly by injecting it.

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 client usage example

Defines how to use the WSClient class to establish a ws connection

@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);
            }
        }
    }
}

3. Actual usage scenarios

1. Use of multiple WSClient connections

The above is a simple demo that can connect to the websocket interface through the client, but the actual scenario may be that many users access the local service, and the service needs to call the remote ws interface. At this time, how to distinguish between independent websocket connections between users?

Idea: Define a global variable to store the websocket client, the client triggers the sending message event, and obtains the corresponding client in the global variable to send the message

@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("请根据卖火柴的小女孩生成一个类似的故事");
        }
    }
}

Summarize

The above is the content of SpringBoot's integrated websocket client, which is used for backend services to call websocket requests. The execution of the specific business logic is implemented in the code. Here are only specific demos and examples, and the actual application scenarios still need to be pondered by yourself.

Guess you like

Origin blog.csdn.net/Oaklkm/article/details/130705555