websockets、express.js 和无法建立到服务器的连接 [英] websockets, express.js and can’t establish a connection to the server

查看:49
本文介绍了websockets、express.js 和无法建立到服务器的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于 WSexpress.js 的简单聊天.我收到浏览器无法通过 websockets 连接到服务器的错误.

This is simple chat on WS and express.js. I get the error that the browser can't connect to server via websockets.

客户端连接:

file: rtc.html 
ws = new WebSocket('wss://' + window.location.hostname + '/wr' );
ws.onerror = (error) => { console.log(error); };
ws.onmessage = (message) => {
   . . . 

服务器代码:

const express =   require('express');
const http =      require('http');
const WebSocket = require('ws');

const app = express();

app.get('/rtc', (req, res)=>{
  res.sendFile('/home/user/dev/rtc.html');
});

const server = http.createServer(app);
const wss = new WebSocket.Server({ server:server, path: "/wr" });

. . . 

app.listen(3000);

UPD:问题是由于我在 webrtc 上聊天并在 Mozilla 中测试,Mozilla 没有连接就无法连接https 连接但是 getUserMedia 运行良好.有必要这样写:

UPD: The problem was due to the fact that I was doing chat on webrtc and tested in Mozilla and Mozilla would not connect without https connection however getUserMedia ran fine. It was necessary to write so:

var https = require('https');
var serv = https.createServer(serverConfig, app);

推荐答案

更改自:

app.listen(3000);

到:

server.listen(3000);

当您使用 app.listen() 时,它会创建一个新的 http 服务器,因此您连接 socket.io 的那个服务器永远不会启动.为了完全理解app.listen(),它的代码如下所示:

When you use app.listen(), it creates a new http server and thus the one you connected socket.io to is never started. To fully understand app.listen(), the code for it looks like this:

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

因此,您可以看到它正在创建一个与您将 webSocket 服务器连接到的 http 服务器不同的 http 服务器,因此另一个从未启动过.

So, you can see it was creating a different http server than the one you attached your webSocket server to and thus that other one was never started.

或者,您也可以这样做:

Alternatively, you could also do this:

const server = app.listen(3000);
const wss = new WebSocket.Server({ server:server, path: "/wr" });

而且,根本不要创建自己的 http 服务器.app.listen() 返回它创建的新服务器对象.

And, not create your own http server at all. app.listen() returns the new server object that it created.

这篇关于websockets、express.js 和无法建立到服务器的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆