【问题标题】:Firefox can’t establish a connection to the server at ws://localhost:8080/Firefox 无法在 ws://localhost:8080/ 建立与服务器的连接
【发布时间】:2018-02-21 10:57:41
【问题描述】:

我有两个文件,一个是test.html,它是:

<script src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
  
$(function () {
  // if user is running mozilla then use it's built-in WebSocket
  window.WebSocket = window.WebSocket || window.MozWebSocket;

  var connection = new WebSocket('ws://localhost:8080/');

  connection.onopen = function () {
    // connection is opened and ready to use
    alert('connection Open');
  };

  connection.onerror = function (error) {
    // an error occurred when sending/receiving data
    alert('Error');
  };

  connection.onmessage = function (message) {
    alert('Message');
    
  };
});

</script>

还有一个nodejs文件是

var WebSocketServer = require('websocket').server;
var http = require('http');
 
var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(8080, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});


wsServer = new WebSocketServer({
    httpServer: server,
    
    autoAcceptConnections: false
});
function originIsAllowed(origin) {
 return true;
}
 
wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }
    
    var connection = request.accept('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
        console.log(message);
        connection.sendBytes(message);
       
    });
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

当我尝试使用我的 HTML 文件连接 web-socket 时,它给了我一个错误

Firefox can’t establish a connection to the server at ws://localhost:8080/

【问题讨论】:

  • node.js服务器的日志?

标签: javascript node.js websocket


【解决方案1】:

它应该能够找到并连接到服务器,但由于服务器文件中的request.accept('echo-protocol', request.origin),服务器将拒绝您的请求并关闭。

检查你的 nodejs 命令提示符的日志。

要解决这个问题,只需修改

var connection = new WebSocket('ws://localhost:8080/');

var connection = new WebSocket('ws://localhost:8080/', 'echo-protocol');

【讨论】:

    猜你喜欢
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 2020-04-06
    • 2012-02-06
    • 2020-09-06
    • 1970-01-01
    相关资源
    最近更新 更多