whycxzp
2025-05-28 5826c5028d061efb0c2c8c7eeaf31a9bca535d7a
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
48
49
50
51
52
53
54
55
package com.whyc.webSocket.receiver;
 
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.WebSocketHttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
 
import javax.annotation.PostConstruct;
import java.net.URI;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
 
@Service
public class WebSocketClientService {
 
    /*@Value("${third.party.websocket.uri}")
    private String webSocketUri;*/
 
    @Autowired
    private ThirdPartyWebSocketHandler handler;
 
    public WebSocketClientService(ThirdPartyWebSocketHandler handler) {
        this.handler = handler;
    }
 
    private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
 
    @PostConstruct
    public void connect() {
        scheduler.scheduleAtFixedRate(() -> {
            try {
                //创建URI对象并将webSocketUri传入
                //String webSocketUri = "ws://localhost:8919/fg/server";
                String webSocketUri = "ws://localhost:18080/realtime-data";
                URI  uri = new URI(webSocketUri);
                System.out.println("webSocketUri:"+webSocketUri);
                if (handler.getSession() == null || !handler.getSession().isOpen()) {
                    System.out.println("Connecting to WebSocket server...");
                    StandardWebSocketClient client = new StandardWebSocketClient();
                    ListenableFuture<WebSocketSession> future = client.doHandshake(handler, new WebSocketHttpHeaders(), uri);
                    future.addCallback(session -> {
                        System.out.println("Connected to WebSocket server.");
                    }, ex -> {
                        System.err.println("Failed to connect to WebSocket: " + ex.getMessage());
                    });
                }
            } catch (Exception e) {
                System.err.println("Unexpected error during connection attempt: " + e.getMessage());
            }
        }, 0, 60, TimeUnit.SECONDS); // 每60秒尝试重连一次
    }
}