我想输入一个具有多个该类型子网址(www.google.com/123或www.google.com/3212)的网站,每当我输入每个子网址时,websocket请求网址都是不同的,这是第一点,第二点是我想获取从这个websocket收到的数据, 该网站从 websocket 接收 3 条二进制消息,我想读取这些二进制消息。就这么简单,能做到吗?
我尝试使用 javascript,但我始终需要一个新的请求网址。
您可以尝试一下以下代码片段吗?
// Replace 'wss://example.com/' with the actual WebSocket URL base
const baseUrl = 'wss://example.com/';
// Replace '123' and '3212' with your specific sub-URLs
const subUrls = ['123', '3212'];
// Function to create WebSocket connection for a given sub-URL
function connectWebSocket(subUrl) {
const socketUrl = baseUrl + subUrl;
const socket = new WebSocket(socketUrl);
// Event listener for WebSocket connection open
socket.addEventListener('open', (event) => {
console.log(`Connected to WebSocket at ${socketUrl}`);
});
// Event listener for WebSocket binary messages
socket.addEventListener('message', (event) => {
// Assuming the data is received as an ArrayBuffer
const binaryData = event.data;
console.log(`Received binary data for ${socketUrl}:`, binaryData);
// Add your binary data processing logic here
});
// Event listener for WebSocket connection close
socket.addEventListener('close', (event) => {
console.log(`WebSocket connection closed for ${socketUrl}`);
});
// Event listener for WebSocket connection error
socket.addEventListener('error', (event) => {
console.error(`WebSocket error for ${socketUrl}:`, event);
});
}
// Connect to each WebSocket with different sub-URLs
subUrls.forEach((subUrl) => {
connectWebSocket(subUrl);
});