【问题标题】:Cannot connect to websocket from website using Nodejs within browser无法在浏览器中使用 Nodejs 从网站连接到 websocket
【发布时间】:2018-12-18 11:19:48
【问题描述】:

有没有人幸运地在 Fastcomet 上使用 Nodejs 和 websockets 创建了一个具有实时通信(聊天)功能的网站?我已经向 Fastcomet 提交了很多票,但我们一直在绕圈子。

我的目标是在 www.mywebsite.com/socketio 上发布类似 https://davidwalsh.name/websocket 的内容

当我在浏览器中打开 http://127.0.0.1:3000/ 时,我的所有测试都在本地运行。

我首先设置了一个Node.js app from cpanel

然后fill in the details

此过程为 Phusion Passenger 创建一个 .htaccess 文件。

甚至尝试过 RewriteRule ^(.) http://localhost:3000/$1 [P]*

当我访问 www.mywebsite.com/socketio 时,我收到以下错误:

http://www.mywebsite:3000/socket.io/?EIO=3&transport=polling&t=1531226905601-0 加载资源失败:net::ERR_NAME_NOT_RESOLVED

这是另一个失败的测试:

服务器 index.js(Nodejs 状态:已启动)

var http = require('http');
var server = http.createServer(function(req, res) {
   res.writeHead(200, {'Content-Type': 'text/plain'});
   var message = 'It works!\n',
       version = 'NodeJS ' + process.versions.node + '\n',
       response = [message, version].join('\n');
   res.end(response);
});
server.listen();
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
 ws.on('message', function incoming(message) {
  console.log('received: %s', message);
 });
 ws.send('something')
});

客户端索引.html

<html>
<head>
    <script>
        var sock =new WebSocket('ws://' + window.location.host+"/chat" );
    </script>
</head>
<body>
</body>
</html>

尝试过

var sock =new WebSocket('ws://' + window.location.host+":8080/chat" );

我还将 index.js 和 index.html 的端口 8080 更改为 3000

我什至从 index.js 和 index.html 中删除了端口

通过浏览器访问:

http://www.mywebsite.com/chat/index.html

错误:

与“ws://www.mywebsite.com/chat”的 WebSocket 连接失败:WebSocket 握手期间出错:意外响应代码:500

有人有想法吗?

【问题讨论】:

  • 你有没有想过这个问题? ERR_NAME_NOT_RESOLVED 可能表示 DNS 设置不正确或由于某种原因无法访问该域。您是否可以通过访问mywebsite.com 正常访问您的域?您是否尝试过不输入 www 而只输入域部分?

标签: node.js websocket chat


【解决方案1】:

您是否尝试在 public_html 文件夹之外创建项目?

尝试创建一个文件夹(例如:home/user/socket_test)并将您的代码放入该文件夹并将您的 node.js 应用程序指向该路径。

端口在“Phusion Passenger”中自动映射,这意味着您在程序中指定的任何端口都将由 phusion 乘客自动反向映射。

节点应用使用端口 3000,example.com/app 将端口 8080 映射到端口 3000。

我正在使用 Fastcommet 共享托管计划并运行 node express RESTful API,并且运行良好。

【讨论】:

  • 您能否提供有关您的设置的更多信息?这是我的设置。应用程序根目录:home/user/socket_test。应用程序 URL:[mydomain]/wschat。应用程序启动文件:index.js。 index.html: 新的 WebSocket("wss://[mydomain]:3000/wschat")。错误:到 'wss://[mydomain]:3000/wschat' 的 WebSocket 连接失败:连接建立错误:net::ERR_CONNECTION_REFUSED。
  • 您能否提供更多关于您如何使用它的信息?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
  • 2014-07-20
  • 2015-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多