gpt4 book ai didi

phpwebsockets yii 实现

转载 作者:行者123 更新时间:2023-11-28 02:00:33 25 4
gpt4 key购买 nike

我正在尝试使用 php 实现 websocket 并将其作为 yii 的扩展,以便我可以为我的 web 应用程序创建类似通知的功能

下面链接中的代码是我的起点:

http://www.flynsarmy.com/2012/02/php-websocket-chat-application-2-0/

它在我本地的 xampp 中完美运行..

我尝试将其转换为我遵循的 Yii 扩展步骤..

  1. 我已经将 PHPWebSocket.php 类放在 yii 扩展文件夹中..
  2. 我创建了一个 Controller websocket 和一个 Action startserver 和一个 Action 索引(用于聊天界面来测试上面链接中的示例)

这是代码片段

<?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 或任何其他脚本

最佳答案

在 Apache 中使用 PHP 时,对 PHP 的每个请求(通常)都会创建新的进程/线程。由于 Web 套接字是(某种程度上)永久连接,因此这些 PHP 请求会持续相当长的一段时间。每个进程都占用服务器上的内存。因此,我认为这是可能的,如果您同时有许多(甚至不是那么多)用户在线,您的服务器可能会崩溃或拒绝请求。

Node.js 方法不同 - 每个连接不需要单独的进程,因此它可以同时处理许多事件连接。

您可以将 Node.js 与 PHP 结合使用,使用队列或其他一些通信机制连接这两者。

关于phpwebsockets yii 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14183387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com