我正在尝试使用 php 实现 websocket 并作为 yii 的扩展,以便我可以为我的 web 应用程序创建类似通知的功能
下面链接中的代码是我的起点:
http://www.flynsarmy.com/2012/02/php-websocket-chat-application-2-0/
它在我当地的 xampp 中完美运行。
我尝试将其转换为我遵循的 Yii 扩展步骤..
- 我已将 PHPWebSocket.php 类放在 yii 扩展文件夹中。
- 我创建了一个控制器 websocket 和一个动作 startserver 和一个动作索引(用于聊天界面以测试上面链接中的示例)
这是代码片段
<?php
Yii::import("ext.websocket.PHPWebSocket");
class WebSocketController extends Controller {
public $layout = '//layouts/empty';
public function actionStartServer() {
set_time_limit(0);
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.");
}
$Server = new PHPWebSocket();
$Server->bind('message', 'wsOnMessage');
$Server->bind('open', 'wsOnOpen');
$Server->bind('close', 'wsOnClose');
$Server->wsStartServer('127.0.0.1', 9300);
}
public function actionIndex() {
$this->render('index');
}
}
我使用 php 创建 websocket 的方法是正确的还是不可能这样做..
我只想使用 php 来实现相同的功能,因为我更喜欢使用 node.js 或任何其他脚本