php - 如何在 websockets php 中创建事件?

标签 php javascript websocket

我正在测试一些 websockets,但我在创建一些触发器/事件时遇到了问题。

我不确定这是否可行,但我只是想尝试一下。

所以我已经下载了一个示例,目前我只是在玩弄它

这是 server.php 的样子:

<?php
include("C:\wamp\www\social\index.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;

$Server->log('received message from ' . $Server->wsClients[$clientID]['user']);

$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 ){
    $item = wire('pages')->get('template=item');
    $Server->wsSend($clientID, "There isn't anyone else in the room, but I'll  still listen to you. --Your Trusty Server");
    $Server->wsSend($clientID, $clientID);
}
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->wsClients[$clientID]['user'] = wire('user')->name;
$Server->log( "$ip ($clientID) has connected. Username: " . $Server-   >wsClients[$clientID]['user'] );

//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.");
}

function wsOnTest($clientID, $status) {
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );

$Server->log("Custom message");

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

// start the server 
$Server = new PHPWebSocket();
$Server->bind('message', 'wsOnMessage');
$Server->bind('open', 'wsOnOpen');
$Server->bind('close', 'wsOnClose');
$Server->bind('test', 'wsOnTest');
// 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('127.0.0.1', 9300);

?>

这是带有简单聊天应用程序的 index.html。正如您在 server.php 和此文件中看到的那样,我试图通过创建事件或名为 test 的函数来愚弄。

    <!doctype html>
<html>
<head>
    <meta charset='UTF-8' />
    <style>
        input, textarea {border:1px solid #CCC;margin:0px;padding:0px}

        #body {max-width:800px;margin:auto}
        #log {width:100%;height:400px}
        #message {width:100%;line-height:20px}
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="fancywebsocket.js"></script>
    <script>
        var Server;

        function log( text ) {
            $log = $('#log');
            //Add text to log
            $log.append(($log.val()?"\n":'')+text);
            //Autoscroll
            $log[0].scrollTop = $log[0].scrollHeight - $log[0].clientHeight;
        }

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

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

        $(document).ready(function() {
            log('Connecting...');
            Server = new FancyWebSocket('ws://127.0.0.1:9300');

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

                    $(this).val('');
                }
            });

            //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.bind('test', function( payload ) {
                log( payload );
            });

            Server.connect();
        });
    </script>
</head>

<body>
    <div id='body'>
        <textarea id='log' name='log' readonly='readonly'></textarea><br/>
        <input type='text' id='message' name='message' />
    </div>
</body>

</html>

为了完整起见,fancywebsocket.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 )
        }
    }
};

那么我如何制作一个事件,就像消息一样,例如发布或其他东西,或者我是否需要发送数组(json)和 json 中的信息,我不想......

提前致谢!

最佳答案

我不想这么说,但您可能应该使用 JSON。 websocket 协议(protocol)没有定义有效负载的结构,因此没有“websocket”方式来做到这一点。但这之前已经在 WAMP Standard 中完成了。 ,他们确实用 JSON 做到了,特别是一个 JSON 数组,第一个项目标识消息类型,例如欢迎消息:

[ TYPE_ID_WELCOME , sessionId , protocolVersion, serverIdent ]

我认为更灵活的实现(您已经提到过)是这样的

{"name": "overTheLine", "message": "Mark it 8, Dude."}

所以你可以做类似的事情

// when a client sends data to the server
function wsOnMessage($clientID, $message, $messageLength, $binary) {
    $messageObj = json_decode($message);
    if (property_exists($messageObj, 'name') 
        and property_exists($messageObj, 'message') 
        and is_callable($messageObj->name)) {
        $messageObj->name($messageObj->message);
    }
...
}

// over the line response
function overTheLine($msg) {
    return "Mark it zero!";
}

客户端也是如此。

关于php - 如何在 websockets php 中创建事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16833992/

相关文章:

javascript - Ember.js 中的类和对象混淆

spring-boot - 托管在 Azure 上的 Spring Boot 网站上的 Websockets 返回错误 503/403

node.js - 使用 NodeJS 的简单 WebSocket 应用程序

php - 重定向后在 codeigniter 中销毁 session

php - 我可以使用外键限制来使用 PHP 返回有意义的 UI 错误吗

php - 导出div内容到图片

php - http/javascript/php 在 C 中执行后

javascript - JS 无法通过 AJAX 调用正确执行

tomcat - 受防火墙保护的 ActiveMQ 服务器的 WS 代理

php - 关于错误参数 PDO 的 MySQL 和 PHP