我正在尝试使用php实现websocket,并将其作为yii的扩展,这样我就可以为我的web应用程序创建类似于通知的功能。
下面的代码是我的起点:
http://www.flynsarmy.com/2012/02/php-websocket-chat-application-2-0/
它在我当地的xampp上运行得很好。
我试着把它转换成我遵循的Yii扩展步骤。
下面是代码片段
<?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或任何其他脚本。
发布于 2013-01-06 15:28:26
当将PHP与Apache结合使用时,每个对PHP的请求(通常)都会创建新的进程/线程。由于web套接字是(某种程度上)永久连接,这些PHP请求会持续相当一段时间。每个进程都会占用服务器上的内存。因此,正如我认为这是可能的,您的服务器可能只是崩溃或拒绝请求,如果您将有许多(甚至没有那么多)用户在线一次。
Node.js方法是不同的-每个连接不需要单独的进程,因此它可以同时处理多个活动连接。
您可以使用Node.js与PHP一起使用队列或其他通信机制连接这两个模块。
发布于 2014-03-18 22:25:23
以防别人发现这件事。
我正在寻找一种方法来实现实时事件到Yii应用程序。
在上面的注释中提到了本(Yii) HTML5 SSE教程。因为这看起来很简单,如果你需要支持旧的浏览器和移动设备,这是不够的。
浏览器支持,也就是它在IE中工作吗?、Internet和Android (所有版本)都不支持服务器发送的事件。旧版本的Firefox (< 6)、Chrome (< 6)、Safari (< 5)、iOS Safari (< 4)或Opera (< 11)也是如此。
另一个解决方案是一个相当新的Yii节点插座扩展。它基于node.js socket.io库,并使用elephant.io通过php与服务器进行通信。最重要的是,这个扩展(我只使用了一个月)似乎写得很好。它同时支持Linux和Windows,使用CLI执行命令,甚至提供了自己的数据库驱动程序。
其他解决办法仍然值得欢迎。
https://stackoverflow.com/questions/14183387
复制相似问题