如何从不同的服务器连接到websocket? [英] How to connect to a websocket from a different server?

查看:80
本文介绍了如何从不同的服务器连接到websocket?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有服务器A windows 7 Pro,我安装了 node.js 并使用此命令运行它 node ws_server.js 按照此处的说明操作

I have server A "windows 7 Pro" where I installed node.js and ran it using this command node ws_server.js following the instructions here

服务器B Windows Server 2008 R2运行Apache 2.4 / php 5.6.13我想连接到服务器A 上的 ws_server

From server B "Windows Server 2008 R2" running Apache 2.4/php 5.6.13 I want to connect to the ws_server on Server A.

**服务器B *我有一个名为 websocket.php 的脚本,代码如下

on **Server B* I have a script called websocket.php with the code below

<script>

        $(function() {

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

            var client = new WebSocketClient();

            client.on('connectFailed', function(error) {
                console.log('Connect Error: ' + error.toString());
            });

            client.on('connect', function(connection) {
                console.log('WebSocket Client Connected');
                connection.on('error', function(error) {
                    console.log("Connection Error: " + error.toString());
                });
                connection.on('close', function() {
                    console.log('echo-protocol Connection Closed');
                });
                connection.on('message', function(message) {
                    if (message.type === 'utf8') {
                        console.log("Received: '" + message.utf8Data + "'");
                    }
                });

                function sendNumber() {
                    if (connection.connected) {
                        var number = Math.round(Math.random() * 0xFFFFFF);
                        connection.sendUTF(number.toString());
                        setTimeout(sendNumber, 1000);
                    }
                }
                sendNumber();
            });

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

    </script>

但由于某种原因,我在控制台中收到此错误。

But for some reason I get this error in the console.


ReferenceError:require未定义

ReferenceError: require is not defined

我是否需要从服务器A的nodejs文件夹中获取文件并将其包含在客户端脚本中?如果是这样我需要包含哪些文件?

Do I need to take files from the nodejs folder from server A and include it in the client script? if so which files do I need to include?

注意:我也包含了jQuery文件

Note: I have included jQuery files as well

已编辑

这是我的客户代码

       <script>
            "use strict";
            // Initialize everything when the window finishes loading
            window.addEventListener("load", function(event) {
              var status = document.getElementById("status");
              var url = document.getElementById("url");
              var open = document.getElementById("open");
              var close = document.getElementById("close");
              var send = document.getElementById("send");
              var text = document.getElementById("text");
              var message = document.getElementById("message");
              var socket;

              status.textContent = "Not Connected";
              url.value = "ws://serverB:8080";
              close.disabled = true;
              send.disabled = true;

              // Create a new connection when the Connect button is clicked
              open.addEventListener("click", function(event) {
                open.disabled = true;
                socket = new WebSocket(url.value, "echo-protocol");

                socket.addEventListener("open", function(event) {
                  close.disabled = false;
                  send.disabled = false;
                  status.textContent = "Connected";
                });

                // Display messages received from the server
                socket.addEventListener("message", function(event) {
                  message.textContent = "Server Says: " + event.data;
                });

                // Display any errors that occur
                socket.addEventListener("error", function(event) {
                  message.textContent = "Error: " + event;
                });

                socket.addEventListener("close", function(event) {
                  open.disabled = false;
                  status.textContent = "Not Connected";
                });
              });

              // Close the connection when the Disconnect button is clicked
              close.addEventListener("click", function(event) {
                close.disabled = true;
                send.disabled = true;
                message.textContent = "";
                socket.close();
              });

              // Send text to the server when the Send button is clicked
              send.addEventListener("click", function(event) {
                socket.send(text.value);
                text.value = "";
              });
            });
  </script>


推荐答案

Taxicala答案是正确的,你不需要。
我认为您可以尝试这段代码以查看套接字是否正常工作

Taxicala answer is correct, you dont need require. I think that you could try this piece of code in order to see if the sockets are working

 var ws = new WebSocket('wss://ServerA:8080/', 'echo-protocol');
 ws.onopen = function () {
     console.log('socket connection opened properly');
     ws.send("Hello World"); // send a message
     console.log('message sent');
 };

 ws.onmessage = function (evt) {
     console.log("Message received = " + evt.data);
 };

 ws.onclose = function () {
     // websocket is closed.
     console.log("Connection closed...");
 };

为了避免安全错误,您应该将Web套接字服务器创建为https而不是http,这是您在相关链接中提供的代码,它适用于生成一个安全服务器,允许所有站点和方法的CORS,它仅用于测试建议。

In order to avoid the security error you should create the web socket server as https instead of http, This is the code that you provided in the related links, it is adapted to generate a secure server that allow CORS for all sites and methods, its only for testing proposes.

请注意,您需要生成证书,并将其存储在名为certs2的文件夹中,如果您需要创建证书的说明只需google一点,那就有很多很好的答案。

Note that you need to generate the certificates, and store it in a folder named certs2, if you need instructions to create the certs just google a little, there are a lot of great answer for that.

//CUSTOM
var WebSocketServer = require('websocket').server;
var https = require('https');
var fs = require('fs');

var options = {
    key: fs.readFileSync('./certs2/key.pem'),
    cert: fs.readFileSync('./certs2/key-cert.pem')
};

var server = https.createServer(options, function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    res.writeHead(404);
    res.end();
});
// END CUSTOM
// START YOUR CODE....
server.listen(8080, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
    // put logic here to detect whether the specified origin is allowed.
    return true;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
        // Make sure we only accept requests from an allowed origin
        request.reject();
        console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
        return;
    }

    var connection = request.accept('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

这篇关于如何从不同的服务器连接到websocket?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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