【问题标题】:WebSocket connection to OpenShift app failedWebSocket 连接到 OpenShift 应用程序失败
【发布时间】:2013-11-25 18:29:35
【问题描述】:

我使用 NodeJS 创建了一个应用程序,并且正在使用 ws 模块。如果我在 localhost 中测试应用程序,它可以工作并且连接 websockets 没有任何问题。现在我已将应用程序上传到 Openshift,当我尝试从客户端访问时,它返回无法建立与 websocket 的连接。

如果我在我的应用程序的腻子中添加尾部,我会收到以下消息:DEBUG:这种类型的响应不能有正文。忽略传递给 end() 的数据。

我在服务器中的代码是:

#!/bin/env node

//Openshift variables
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "192.168.69.42";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;


//NodeJS require modules
var Enum = require('enum');
var WebSocketServer = require('ws').Server
    wss = new WebSocketServer({host:ipaddress, port:port});
var fs = require('fs');


wss.on('connection', function(ws) {
    console.log((new Date()) + ' Connection from origin: ' + ws._socket.remoteAddress);
});

console.log((new Date()) + " Server is listening on: " + ipaddress + ':' port);

在客户端:

var ws = new WebSocket("ws://192.168.69.42:8080/");

ws.onopen = function() {
    console.log("Connected.");
    ws.send("This is the client speaking.");
};

【问题讨论】:

  • 您在客户端使用本地地址 ws://192.168.69.42:8080/,将其更改为您从 OpenShift 获得的域(使用新域,它看起来像 ws://yourapp-yourname.rhcloud.com/)并添加您的访问范围来自 OPENSHIFT(只需登录并在客户端使用)
  • 我将代码与 localhost url 放在一起。我尝试使用正确的 url 到我的应用程序,这是我遇到错误的时候。
  • 请先检查您的代码。 WebSocketServer = require('ws').Server 之后缺少逗号,加上客户端代码域之前的 concat 行 console.log((new Date()) + " Server is listening on: " + ipaddress + ':' port);//。很难重现您的错误以提供帮助。
  • 对错误感到抱歉,我已修复它们并继续发生

标签: javascript node.js websocket openshift


【解决方案1】:

对于 OpenShift 上的所有 WebSocket 连接,您需要使用端口 8000(对于安全会话,它将是 8443)。因此,您的服务器示例运行良好(我在删除不必要的行 var Enum = require('enum'); 后运行它们,您只需将客户端上的端口硬编码为 8000

var ws = new WebSocket("ws://YourApp-YourName.rhcloud.com:8000"); 

ws.onopen = function(){
  console.log('opened')
}

更多信息here

【讨论】:

    【解决方案2】:

    这是 github 上的一个示例,您可以查看:https://github.com/developercorey/openshift-nodejs-http-and-websocket-example

    【讨论】:

    猜你喜欢
    • 2021-06-19
    • 1970-01-01
    • 2020-11-23
    • 2018-12-19
    • 1970-01-01
    • 2022-10-17
    • 2016-04-20
    • 2013-12-17
    相关资源
    最近更新 更多