企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
**一.Socket资源迁移到Socket对象** #php可使用socket编写成熟的服务器端程序   **二.查看类型** ``` $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); ```   **三.socket编程** #默认php中的socket是单进程通讯 #启用pcntl模块可支持多进程通讯 1.创建socket对象 ``` $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); ``` 2.进程监听ip和端口 ``` socket_bind($socket,'192.168.2.1',20004); socket_listen($socket); ``` 3.生成客户端连接 ``` $connection = socket_accept($socket); ``` 4.获取客户端信息 ``` socket_getpeername($connection,$cip,$cport); ``` 5.设置欢迎语 ``` $buffer = "Welcome To PHP8\n"; if($buffer != ""){ socket_write($connection,"{$buffer}\n"); } ``` 6.从客户端读取数据 ``` $data = socket_read($connection, 1024,PHP_NORMAL_READ) ``` 7.服务端打印数据 ``` printf("{$cip}:{$cport}-->{$buffer}\n"); ``` 8.向客户端写入数据 ``` socket_write($connection,"{$cip}:{$cport}-->{$buffer}\n"); ``` 9.客户端连接断开 ``` socket_close($connection); printf("{$cip}:{$cport} disconnected\n"); ```   **四.socket单进程完整实例** ``` $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); socket_bind($socket,'192.168.2.1',20004); socket_listen($socket); while(true){ $connection = socket_accept($socket); socket_getpeername($connection,$cip,$cport); $buffer = "Welcome To PHP8\n"; if($buffer != ""){ socket_write($connection,"{$buffer}\n"); } while($data = socket_read($connection, 1024,PHP_NORMAL_READ)){ $buffer = $data; printf("{$cip}:{$cport}-->{$buffer}\n"); socket_write($connection,"{$cip}:{$cport}-->{$buffer}\n"); } socket_close($connection); printf("{$cip}:{$cport} disconnected\n"); } ```   **五.socket程序商用** #php.ini ``` display_errors = Off ```