[英]websockets, express.js and can’t establish a connection to the server
This is simple chat on WS and express.js
. 这是在WS和
express.js
上的简单聊天。 I get the error that the browser can't connect to server via websockets
. 我收到浏览器无法通过
websockets
连接到服务器的错误。
client connection: 客户端连接:
file: rtc.html
ws = new WebSocket('wss://' + window.location.hostname + '/wr' );
ws.onerror = (error) => { console.log(error); };
ws.onmessage = (message) => {
. . .
Server code: 服务器代码:
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: 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. UPD:问题是由于我在
webrtc
上进行聊天并在Mozilla
进行了测试,并且在没有https
连接的情况下Mozilla
无法连接,但是getUserMedia
运行良好。 It was necessary to write so: 有必要这样写:
var https = require('https');
var serv = https.createServer(serverConfig, app);
Change from: 更改自:
app.listen(3000);
to: 至:
server.listen(3000);
When you use app.listen()
, it creates a new http server and thus the one you connected socket.io to is never started. 当您使用
app.listen()
,它将创建一个新的http服务器,因此永远不会启动与socket.io连接的服务器。 To fully understand app.listen()
, the code for it looks like this: 要完全了解
app.listen()
,其代码如下所示:
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
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. 因此,您可以看到它正在创建与将webSocket服务器连接到的http服务器不同的http服务器,因此从未启动其他服务器。
Alternatively, you could also do this: 或者,您也可以这样做:
const server = app.listen(3000);
const wss = new WebSocket.Server({ server:server, path: "/wr" });
And, not create your own http server at all. 而且,根本不要创建自己的http服务器。
app.listen()
returns the new server object that it created. app.listen()
返回它创建的新服务器对象。
just make sure you use server.listen().Rest the code speaks itself 只要确保您使用server.listen()。Rest代码就可以了
var express = require('express'), app = express(), http = require('http'), server = http.createServer(app), WebSocketServer = require('ws').Server, wss = new WebSocketServer({ server }); app.use(express.static(__dirname)); server.listen(process.env.PORT || 3000, function () { // console.log("Node server is running on http://localhost:3000/"); }); wss.on('connection', function (ws) { //console.log("New connection."); ws.on('message', function (message) { //console.log("Message received:", message); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.