将websocket数据发送到任意客户端(基于例如用户名)

时间:2013-04-23 22:55:50

标签: websocket

使用websockets可以实现以下目标:

  • UserA和UserB是网站的用户。
  • UserA登录该站点并启动websocket连接。
  • UserB有一条UserA的消息,所以他们提交一个由服务器上的某个脚本处理的表单(无论是通过WS,XHR还是只是简单的形式)
  • 服务器通过websocket连接向UserA发送消息 - 没有服务器代码只是不断检查数据库是否有新消息。

理想情况下,处理邮件发送的脚本会执行所有操作 - 将邮件放入数据库并将其发送到收件人的websocket连接。

编辑:这是我对这种功能的实际情况:

我正在开发一个国际象棋网站,目前使用长轮询来更新用户,当他们的对手移动时,以及其他一些东西,如棋盘下方的聊天框。

这是用户调用移动的PHP脚本,添加了代码(接近结尾)以说明我想要做的事情:

/xhr/move.php

<?php
require_once "base.php";
require_once "Data.php";
require_once "php/livechess/LiveGame.php";
require_once "php/init.php";

$result=false;

if($session->user->signedin()) {
    $q=Data::unserialise($_GET["q"]);

    if(isset($q["gid"]) && isset($q["fs"]) && isset($q["ts"])) {
        $colour=Db::cell("
            select colour from seats
            where user='{$session->user->username}'
            and gid='{$q["gid"]}'
            and type='".SEAT_TYPE_PLAYER."'
        ");

        if($colour!==false) {
            $promote_to=QUEEN;

            if(isset($q["promote_to"])) {
                $promote_to=$q["promote_to"];
            }

            $game=new LiveGame($q["gid"]);

            if($game->position->active===$colour) {
                if($game->move($q["fs"], $q["ts"], $promote_to)->success) {
                    $result=$game->history->main_line->last_move->mtime;
                    $game->check_premoves();
                    $game->save();

                    /*
                    here is where the functionality I'm talking to would come in:

                    (some pseudocode for brevity)
                    */

                    $opponent_username=Db::cell("select user from seats where colour=".opp_colour($colour)." and etc");

                    send_websocket_data($opponent_username, Data::serialise($game->history->main_line->last_move));
                }
            }
        }
    }
}

echo Data::serialise($result);
?>

我不知道send_websocket_data函数的实现是什么样的,除了需要用户名和一些数据才能发送。

1 个答案:

答案 0 :(得分:1)

是websocket安装与连接的客户端的全双工连接。所以服务器可以随时向他们发送消息。

然后,实现取决于您的客户端和服务器。

你似乎喜欢php,你可以看看Ratchet。我没试过。

您还可以阅读websockets

另请注意,websockets无法在任何地方使用,具体取决于网络代理。因此,您可能必须处理长时间轮询的优雅降级。这是异步框架提供的,但在其他语言中(大气/ java,Socket.oi / node.js)

Websockets很酷! Goog运气:))