gpt4 book ai didi

php - 我的基本PHP Socket Server是否需要优化?

转载 作者:行者123 更新时间:2023-12-03 11:56:23 25 4
gpt4 key购买 nike

像许多人一样,我可以使用PHP做很多事情。我一直面临的一个问题是,其他人可以做到更清洁,更有条理,更有条理。这也导致更快的执行时间和更少的错误。

我刚刚完成基本的PHP Socket Server(真正的核心)的编写,然后问您是否可以告诉我在开始扩展核心之前应该做些什么。我并不是在问诸如加密数据,身份验证或多线程之类的改进。

我更想知道这样的问题:“我应该以一种面向对象的方式(使用PHP5)吗?”,或者“脚本运行方式的总体结构是否良好,还是应该做一些不同的事情?” 。基本上,“这是套接字服务器核心的工作方式吗?”

实际上,我认为,如果我仅在此处向您显示代码,则许多人将立即看到需要改进的地方。请告诉我。谢谢!

#!/usr/bin/php -q
<?
// config
$timelimit = 180; // amount of seconds the server should run for, 0 = run indefintely
$address = $_SERVER['SERVER_ADDR']; // the server's external IP
$port = 9000; // the port to listen on
$backlog = SOMAXCONN; // the maximum of backlog incoming connections that will be queued for processing

// configure custom PHP settings
error_reporting(1); // report all errors
ini_set('display_errors', 1); // display all errors
set_time_limit($timelimit); // timeout after x seconds
ob_implicit_flush(); // results in a flush operation after every output call

//create master IPv4 based TCP socket
if (!($master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) die("Could not create master socket, error: ".socket_strerror(socket_last_error()));

// set socket options (local addresses can be reused)
if (!socket_set_option($master, SOL_SOCKET, SO_REUSEADDR, 1)) die("Could not set socket options, error: ".socket_strerror(socket_last_error()));

// bind to socket server
if (!socket_bind($master, $address, $port)) die("Could not bind to socket server, error: ".socket_strerror(socket_last_error()));

// start listening
if (!socket_listen($master, $backlog)) die("Could not start listening to socket, error: ".socket_strerror(socket_last_error()));

//display startup information
echo "[".date('Y-m-d H:i:s')."] SERVER CREATED (MAXCONN: ".SOMAXCONN.").\n"; //max connections is a kernel variable and can be adjusted with sysctl
echo "[".date('Y-m-d H:i:s')."] Listening on ".$address.":".$port.".\n";
$time = time(); //set startup timestamp

// init read sockets array
$read_sockets = array($master);

// continuously handle incoming socket messages, or close if time limit has been reached
while ((!$timelimit) or (time() - $time < $timelimit)) {
$changed_sockets = $read_sockets;
socket_select($changed_sockets, $write = null, $except = null, null);
foreach($changed_sockets as $socket) {
if ($socket == $master) {
if (($client = socket_accept($master)) < 0) {
echo "[".date('Y-m-d H:i:s')."] Socket_accept() failed, error: ".socket_strerror(socket_last_error())."\n";
continue;
} else {
array_push($read_sockets, $client);
echo "[".date('Y-m-d H:i:s')."] Client #".count($read_sockets)." connected (connections: ".count($read_sockets)."/".SOMAXCONN.")\n";
}
} else {
$data = @socket_read($socket, 1024, PHP_NORMAL_READ); //read a maximum of 1024 bytes until a new line has been sent
if ($data === false) { //the client disconnected
$index = array_search($socket, $read_sockets);
unset($read_sockets[$index]);
socket_close($socket);
echo "[".date('Y-m-d H:i:s')."] Client #".($index-1)." disconnected (connections: ".count($read_sockets)."/".SOMAXCONN.")\n";
} else {
if ($data = trim($data)) { //remove whitespace and continue only if the message is not empty
switch ($data) {
case "exit": //close connection when exit command is given
$index = array_search($socket, $read_sockets);
unset($read_sockets[$index]);
socket_close($socket);
echo "[".date('Y-m-d H:i:s')."] Client #".($index-1)." disconnected (connections: ".count($read_sockets)."/".SOMAXCONN.")\n";
break;
default: //for experimental purposes, write the given data back
socket_write($socket, "\n you wrote: ".$data);
}
}
}
}
}
}
socket_close($master); //close the socket
echo "[".date('Y-m-d H:i:s')."] SERVER CLOSED.\n";
?>

最佳答案

一件小事,我个人会创建一个输出函数,而不仅仅是使用echo,这样就很容易将其关闭,更改格式等。例如

function log($message = '')
{
echo '['.date('Y-m-d H:i:s').']'.$message;
}

然后您可以使用:
log("SERVER CREATED (MAXCONN: ".SOMAXCONN.").\n");

代替
echo "[".date('Y-m-d H:i:s')."] SERVER CREATED (MAXCONN: ".SOMAXCONN.").\n";

哦,一定要使用===而不是==,否则您可能会得到一些奇怪的结果。

关于php - 我的基本PHP Socket Server是否需要优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1026690/

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