A Solution for Vue Development WebSocket/wss Communication Error: CLOSED => 1006 CLOSE_ABNORMAL
A Vue Development WebSocket/wss Communication Error CLOSED = 1006 CLOSE_ABNORMAL Solution
Test file first:
“`
WebSocket Test Page
Connection Control
Send Message
Connection Info
Log Records
let ws = null;
const logContainer = document.getElementById('logContainer');
const connectionStatus = document.getElementById('connectionStatus');
const disconnectBtn = document.getElementById('disconnectBtn');
function getTimestamp() {
return new Date().toLocaleTimeString();
}
function log(message, type = 'info') {
const timestamp = getTimestamp();
const logEntry = document.createElement('div');
logEntry.innerHTML = ` ${message}`;
logEntry.className = type;
logContainer.appendChild(logEntry);
logContainer.scrollTop = logContainer.scrollHeight;
}
function updateConnectionStatus(message, type) {
connectionStatus.textContent = message;
connectionStatus.className = `status ${type}`;
}
function connectWS(url) {
if (ws) {
log('Closing existing connection...', 'info');
ws.close();
}
try {
log(`Attempting to connect to ${url}...`, 'info');
ws = new WebSocket(url);
ws.onopen = function() {
log('WebSocket connection successful!', 'success');
updateConnectionStatus('Connected', 'success');
disconnectBtn.disabled = false;
};
ws.onclose = function(event) {
let reason = 'Unknown reason';
switch (event.code) {
case 1000:
reason = 'Normal closure';
break;
case 1001:
reason = 'Server closing or client leaving page';
break;
case 1002:
reason = 'Protocol error';
break;
case 1003:
reason = 'Unsupported data type';
break;
case 1006:
reason = 'Unable to connect to server (possibly network issues or server not responding)';
break;
case 1007:
reason = 'Inconsistent data format received';
break;
case 1008:
reason = 'Policy violation';
break;
case 1009:
reason = 'Message too large';
break;
case 1011:
reason = 'Server encountered unexpected error';
break;
default:
reason = `Unknown error (Code: ${event.code})`;
}
log(`WebSocket connection closed. Code: ${event.code}, Reason: ${reason}`, 'error');
updateConnectionStatus('Not Connected', 'info');
disconnectBtn.disabled = true;
ws = null;
// Prompt user about possible solutions
if (event.code === 1006) {
log('Tip: Please check if the server is running, or if the network connection is normal.', 'info');
}
};
ws.onerror = function(error) {
log(`WebSocket error: ${error.message || error}`, 'error');
console.error('WebSocket error:', error);
updateConnectionStatus('Connection Error', 'error');
};
ws.onmessage = function(event) {
log(`Received message: ${event.data}`, 'info');
};
} catch (error) {
log(`Connection error: ${error.message}`, 'error');
updateConnectionStatus('Connection Error', 'error');
}
}
function disconnectWS() {
if (ws) {
ws.close();
log('Connection closed actively', 'info');
}
}
function sendMessage() {
const messageInput = document.getElementById('messageInput');
-
Alipay QR Code Scan
-
WeChat Scan Pay