我正在尝试使我的PHP服务器更有效率。
我建立了一个名为Client
的对象,该对象包含已连接的客户端(与服务器具有开放的套接字连接)信息,例如name
,id
等。
现在,我有一组套接字连接和一组Client对象。
当我引用一个连接时,我正在Client数组中搜索以找到与该连接匹配的正确客户端。
它的效果很好,但是效率有点低。.对于服务器中的少量客户端,您不会感觉到它,但是我担心如果我有成千上万的连接,它将降低服务器的速度。
作为解决方案,我考虑了二维数组,但是在设计二维数组时遇到了逻辑问题。
我可以做这样的事情:
$clients = array();
$temp = array($newsock, new Client());
$clients[] = $temp;
我希望将
$clients[]
用作套接字,并将$clients[][]
用作客户端对象。在
$client
的每一行中,我只有$client[$index][0]
,它将是该连接的客户端对象。我可以将其发送到
socket_select()
函数吗?
最佳答案
您说在客户对象中有一个id
属性。为什么不使用那个id
作为两个数组的键?
您甚至可以将连接和客户端对象保存在一个数组中,每个对象都放在我之前谈到的相同键下的一个对象中-客户端
id
。无论如何,无论您决定存储客户连接对象的什么地方,都可以将其传递给所有相关的套接字函数-
socket_select();
socket_accept();
socket_write();
关于服务器的效率,我实现了一些派生功能,用于向大量客户端广播数据(所有客户端均在聊天服务器示例中)。
这是我用于 fork 广播的实现-
function broadcastData($socketArray, $data){
global $db;
$pid = pcntl_fork();
if($pid == -1) {
// Something went wrong (handle errors here)
// Log error, email the admin, pull emergency stop, etc...
echo "Could not fork()!!";
} elseif($pid == 0) {
// This part is only executed in the child
foreach($socketArray AS $socket) {
// There's more happening here but the essence is this
socket_write($socket,$msg,strlen($msg));
// TODO : Consider additional forking here for each client.
}
// This is where the signal is fired
exit(0);
}
// The child process is now occupying the same database
// connection as its parent (in my case mysql). We have to
// reinitialize the parent's DB connection in order to continue using it.
$db = dbEngine::factory(_dbEngine);
}
上面的代码是从我的上一个问题(即self answered)中提炼出来的。
Terminating zombie child processes forked from socket server
如果您选择开始 fork 过程,它可能会为您提供帮助。
关于php - 具有二维数组的socket_select(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10463774/