wss在apache服务器上进行故障转移

时间:2015-06-16 16:09:55

标签: php ssl websocket wss

我在数字海洋中有一台服务器,它使用StartCOM class I主要中间CA for ssl。我已经设置了一个websocket服务器,我想从一个由https提供服务的页面建立连接。

当我尝试使用http连接到websocket时工作正常。但是,当我尝试通过将websocket uri从ws更改为wss而无法连接时,将其用于https。

我做错了什么。使用fancywebsockets.js进行连接

fancywebsockets.js

var FancyWebSocket = function(url)
{
    var callbacks = {};
    var ws_url = url;
    var conn;

    this.bind = function(event_name, callback){
        callbacks[event_name] = callbacks[event_name] || [];
        callbacks[event_name].push(callback);
        return this;// chainable
    };

    this.send = function(event_name, event_data){
        this.conn.send( event_data );
        return this;
    };

    this.connect = function() {
        if ( typeof(MozWebSocket) == 'function' )
            this.conn = new MozWebSocket(url);
        else
            this.conn = new WebSocket(url);

        // dispatch to the right handlers
        this.conn.onmessage = function(evt){
            dispatch('message', evt.data);
        };

        this.conn.onclose = function(){dispatch('close',null)}
        this.conn.onopen = function(){dispatch('open',null)}
    };

    this.disconnect = function() {
        this.conn.close();
    };

    var dispatch = function(event_name, message){
        var chain = callbacks[event_name];
        if(typeof chain == 'undefined') return; // no callbacks for this event
        for(var i = 0; i < chain.length; i++){
            chain[i]( message )
        }
    }
};

客户端JS

var Server;

        function log( text ) {
        console.log(text) 
    }

        function send( text ) {
            Server.send( 'message', text );
        }

        $(document).ready(function() {
            log('Connecting...');
            Server = new FancyWebSocket('ws://www.myserver.com:9400');

            $('#message').keypress(function(e) {
                if ( e.keyCode == 13 && this.value ) {
                    log( 'You: ' + this.value );
                    send( this.value );


                }
            });

            //Let the user know we're connected
            Server.bind('open', function() {
                log( "Connected." );
            });

            //OH NOES! Disconnection occurred.
            Server.bind('close', function( data ) {
                log( "Disconnected." );
            });

            //Log any messages sent from server
            Server.bind('message', function( payload ) {
                log( payload );
            });

            Server.connect();
        });

Server.php

<?php
// prevent the server from timing out
set_time_limit(0);

// include the web sockets server script (the server is started at the far bottom of this file)
require 'class.PHPWebSocket.php';

// when a client sends data to the server
function wsOnMessage($clientID, $message, $messageLength, $binary) {
    global $Server;
    $ip = long2ip( $Server->wsClients[$clientID][6] );

    // check if message length is 0
    if ($messageLength == 0) {
        $Server->wsClose($clientID);
        return;
    }

    //The speaker is the only person in the room. Don't let them feel lonely.
    if ( sizeof($Server->wsClients) == 1 )
        $Server->wsSend($clientID, "There isn't anyone else in the room, but I'll still listen to you. --Your Trusty Server");
    else
        //Send the message to everyone but the person who said it
        foreach ( $Server->wsClients as $id => $client )
            if ( $id != $clientID )
                $Server->wsSend($id, "Visitor $clientID ($ip) said \"$message\"");
}

// when a client connects
function wsOnOpen($clientID)
{
    global $Server;
    $ip = long2ip( $Server->wsClients[$clientID][6] );

    $Server->log( "$ip ($clientID) has connected." );

    //Send a join notice to everyone but the person who joined
    foreach ( $Server->wsClients as $id => $client )
        if ( $id != $clientID )
            $Server->wsSend($id, "Visitor $clientID ($ip) has joined the room.");
}

// when a client closes or lost connection
function wsOnClose($clientID, $status) {
    global $Server;
    $ip = long2ip( $Server->wsClients[$clientID][6] );

    $Server->log( "$ip ($clientID) has disconnected." );

    //Send a user left notice to everyone in the room
    foreach ( $Server->wsClients as $id => $client )
        $Server->wsSend($id, "Visitor $clientID ($ip) has left the room.");
}

// start the server
$Server = new PHPWebSocket();
$Server->bind('message', 'wsOnMessage');
$Server->bind('open', 'wsOnOpen');
$Server->bind('close', 'wsOnClose');
// for other computers to connect, you will probably need to change this to your LAN IP or external IP,
// alternatively use: gethostbyaddr(gethostbyname($_SERVER['SERVER_NAME']))
$Server->wsStartServer('my.ip.add.ress', 9400);

?>

服务器屏幕截图

enter image description here

它一直在断开连接

1 个答案:

答案 0 :(得分:2)

我遇到了同样的问题(我甚至使用相同的PHP脚本)并设法使用stunnel来解决这个问题。经过各种不同的,矛盾的来源的大量反复试验,我设法让它运行起来。但是,您不再获得客户端IP地址,如果需要,您必须手动将其发送到服务器。我在某个地方读到你可以使用代理转发客户端IP,但还没有能够自己设置它。

在服务器上安装stunnel

通过ssh登录您的服务器,确保您的系统完全是最新的。

Delete object

安装stunnel包

apt-get update
apt-get upgrade

配置stunnel

通过运行以下命令为stunnel创建配置文件

apt-get install stunnel4 -y

将以下内容写入文件

nano /etc/stunnel/stunnel.conf

就我个人而言,我刚刚使用了相同的stunnel证书,就像我为HTTPS设置所做的那样。

运行stunnel

你必须保持stunnel运行,就像你必须保持websocket运行一样。 使用以下命令执行此操作:

foreground = yes
key = /path/to/your/ssl/cert.key
cert =  /path/to/your/ssl/cert.pem
CAfile = /path/to/your/ssl/cert.pem
debug = 7
output = /var/log/stunnel_websocket.log

[websocket]
accept = myserver.com:9401
connect = 9400

更改您的PHP脚本

更改PHP文件server.php

/etc/init.d/stunnel4 restart

$Server->wsStartServer('my.ip.add.ress', 9400);

更改客户端JS脚本

$Server->wsStartServer('localhost', 9400);

应改为

Server = new FancyWebSocket('ws://www.myserver.com:9400');

因此,如果您正在运行stunnel和websocket,您现在应该能够再次通过套接字发送和接收数据,唯一的区别是所有客户端现在看起来都是来自127.0.0.1,根据websocket脚本。 / p>