Ai
1 Star 0 Fork 0

hphper/linux_c

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
socket.php 1.98 KB
Copy Edit Raw Blame History
hkui authored 2022-08-15 09:05 +08:00 . 20220815
<?php
$address = '0.0.0.0';
$port = $argv[1] ?? 8071;
$listen = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (false === $listen) errhandle(__LINE__);
//ctrl+c重启时 能立马重启,要在bind,listen之前
if (true !== socket_set_option($listen, SOL_SOCKET, SO_REUSEADDR, 1)) errhandle(__LINE__);;
if (true !== socket_bind($listen, '0.0.0.0', $port)) errhandle(__LINE__);;
if (true !== socket_listen($listen, 5)) errhandle(__LINE__);; //待连接队列长度
//socket_set_nonblock($listen);
echo "Server linsten on:{$address}:$port" . PHP_EOL;
while (true) {
//连接socket,处理连接的接入
$sock_client = socket_accept($listen);
if (false === $sock_client) {
errhandle(__LINE__,false);
continue;
}
processClientConn($sock_client);
}
//处理已经连入的连接
function processClientConn($sock_client)
{
if (socket_getpeername($sock_client, $clinet_addr, $client_port)) {
echo "New client " . intval($sock_client) . " come from {$clinet_addr}:$client_port" . PHP_EOL;
sayWelcome($sock_client);
}
while (true) {
//接收到不少于len
$len = socket_recv($sock_client, $buf, 2048, 0);
if ($len === false) {
echo "no data" . PHP_EOL;
continue;
} elseif ($len === 0) {
errhandle(__LINE__,false);
socket_shutdown($sock_client);
break;
} else {
echo "recv=" . var_export($buf,1) . ",len=" . $len . PHP_EOL;
$trimBuf=trim($buf);
if ($trimBuf == 'quit') {
socket_shutdown($sock_client);
break;
}
}
}
}
function errhandle($line_num,$exit=true)
{
echo $line_num.":".socket_last_error() . ":" . socket_strerror(socket_last_error()) . PHP_EOL;
if($exit){
exit();
}
}
function sayWelcome($client)
{
$buf = date("H:i:s") . " welcome to server! you id:" . intval($client) . PHP_EOL;
socket_write($client, $buf, strlen($buf));
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C
1
https://gitee.com/hk/process_thread_study.git
git@gitee.com:hk/process_thread_study.git
hk
process_thread_study
linux_c
master

Search