1
我嘗試我的客戶通過網絡JS連接的插座,但我有這個錯誤連接接收握手迴應之前關閉目前對WebSocket
getUser.js:29 WebSocket connection to 'ws://localhost:8005/wsserver.js' failed: Connection closed before receiving a handshake response
但看看我的代碼:
getUser.js
var sock = new WebSocket("ws://localhost:8005/wsserver.js");
$('#data1').append("alors");
sock.onopen = function (event) {
$('#data').append("server status opened" + event.currentTarget.URL);
sock.send(JSON.stringify("coucou"));
console.log("sended");
};
sock.onmessage = function (event) {
$('#data').append(event.data);
console.log(event.data);
};
sock.onerror = function(error) {
console.log('WebSocket Error: ' + error);
};
而服務器端代碼是: wsserver.js
var WebSocketServer = require("ws").Server;
var ws = new WebSocketServer({ port: 8005 });
console.log("Server started...");
ws.on('connection', function (ws) {
console.log("Browser connected online...")
ws.on("message", function (str) {
var ob = JSON.parse(str);
switch(ob.type) {
case 'text':
console.log("Received: " + ob.content)
ws.send('{ "type":"text", "content":"Server ready."}')
break;
case 'image':
console.log("Received: " + ob.content)
console.log("Here is an apricot...")
var path ="apricot.jpg";
var data = '{ "type":"image", "path":"' + path + '"}';
ws.send(data);
break;
}
})
ws.on("close", function() {
console.log("Browser gone.")
})
});
但錯誤仍在這裏,我不明白爲什麼