OpenShift Node.js WebSocket服务器连接问题

时间:2018-07-19 04:37:30

标签: javascript node.js openshift

我试图使用WebSockets连接到在OpenShift上运行的服务器,但是无论我如何配置,似乎都没有任何反应。我尝试通过绑定到80008080的端口来连接端口8080008080,但没有任何结果。

我的客户端尝试连接:

var connection = new WebSocket('ws://trserve-trserver.1d35.starter-us-east-1.openshiftapps.com:8000');
connection.onopen = function() {
  window.alert("Connected!");
};

但是"Connected"永远不会在警报窗口中弹出。在服务器端:

var webSocketsServerPort = process.env.PORT ||
  process.env.OPENSHIFT_NODEJS_PORT || 8080;
var webSocketIP = process.env.IP || process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0';
var server = http.createServer(function(request, response) {});
server.listen(webSocketsServerPort, webSocketIP, function() {
  console.log((new Date()) + " Server is listening on port " +
    webSocketsServerPort);
});
var wsServer = new webSocketServer({
  httpServer: server
});
wsServer.on('request', function(request) {
      console.log((new Date()) + ' Connection from origin ' + request.origin + '.');

服务器打印:

"The server is listening on port 8080"

但从不列出任何带有Connection的内容。

1 个答案:

答案 0 :(得分:0)

客户端

示例1:使用W3C WebSocket API

<fragment
        android:id="@+id/navHostFragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph"/>

示例2:

var W3CWebSocket = require('websocket').w3cwebsocket;

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

client.onerror = function() {
    console.log('Connection Error');
};

client.onopen = function() {
    console.log('WebSocket Client Connected');
};

服务器端:

var WebSocketClient = require('websocket').client;

var client = new WebSocketClient();

client.on('connect', function(connection) {
    console.log('WebSocket Client Connected');
    connection.on('error', function(error) {
        console.log("Connection Error: " + error.toString());
    });
});

client.connect('ws://localhost:8080/', 'echo-protocol');

来源:WebSocket

希望,这可能会对您有所帮助。您只需要逐步进行。最重要的是允许来自客户端请求来源的后端来源。