Firefox 无法在 ws://localhost:8080/ 建立与服务器的连接

Posted

技术标签:

【中文标题】Firefox 无法在 ws://localhost:8080/ 建立与服务器的连接【英文标题】:Firefox can’t establish a connection to the server at 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服务器的日志? 【参考方案1】:

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

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

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

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

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

【讨论】:

以上是关于Firefox 无法在 ws://localhost:8080/ 建立与服务器的连接的主要内容,如果未能解决你的问题,请参考以下文章

CSS 转换在 Firefox 上无法正常工作

linux中firefox 无法启动

.ogg 视频无法在 Firefox 中播放

无法在 Firefox 上从 Javascript 提交表单

无法在 Firefox 中拖动按钮元素

linux下安装opera后firefox无法启动