【发布时间】:2013-01-06 15:05:27
【问题描述】:
我正在尝试使用 php 实现 websocket 并作为 yii 的扩展,以便我可以为我的 web 应用程序创建类似通知的功能
下面链接的代码是我的起点:
http://www.flynsarmy.com/2012/02/php-websocket-chat-application-2-0/
它在我的本地 xampp 中完美运行..
我尝试将其转换为我遵循的 Yii 扩展步骤..
- 我已经把类 PHPWebSocket.php 放到了 yii 扩展文件夹中..
- 我创建了一个控制器 websocket 和一个动作 startserver 和一个动作索引(用于聊天界面测试上面链接中的示例)
这里是代码sn-p
<?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 或任何其他脚本
【问题讨论】:
-
你可以运行命令行应用程序吗?如果是这样,以这种方式运行您的服务器可能会使您的服务器运行时间更长......
-
您无法从控制器中的客户端请求启动 websocket 服务器。您应该从命令行运行服务器并继续运行。
-
嗨@fuzionpro 我看到了这个关于websocket with php 的教程,我想在yii 中实现它。您是否找到了如何将其与 yii 集成的解决方案。谢谢
-
@HADEV 我无法实现 websockets,而是使用了yiiframework.com/wiki/329/…
标签: php html yii websocket yii-extensions