连接在收到握手响应WebSocket之前关闭

时间:2017-02-17 21:14:37

标签: javascript

我试图通过JS中的Web套接字连接我的客户端,但我有这个错误

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.")
    })
});

但错误仍然存​​在,我不明白为什么

1 个答案:

答案 0 :(得分:1)

将脚本部分远离您的客户:

var sock = new WebSocket(" ws:// localhost:8005");

服务器应用程序正在该端口中运行,您只需要连接到该端口。