php socket编程 读完成后写阻塞
socket tcp php server
server端代码 如下:<?phpset_time_limit(0); $host = "127.0.0.1";$port = 12345; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n"); // 创建一个Socket $result = socket_bind($socket, $host, $port) or die("Could not bind tosocket\n"); //绑定Socket到端口 $result = socket_listen($socket) or die("Could not set up socket listener\n"); // 开始监听连接 $spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); // 处理通信//若换成循环接收数据,客户端将一直处理等待接收状态$input = socket_read($spawn, 1024) or die("Could not read data\n");/* while (( $data = socket_read($spawn, 1024)) != false) $input .= $data;*/ echo 'input:', strlen($input), "\n"; $output = date("Y-m-d H:i:s"). "\n"; //处理客户端输入并返回结果 echo "output:", $output, "\n"; // 数据传送 向客户端写入返回结果socket_write($spawn, $output, strlen($output)) or die("Could not write output\n"); // 关闭socketssocket_close($spawn);socket_close($socket);
client端, 代码如下:
<?phpset_time_limit(0); $host = "127.0.0.1";$port = 12345; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)or die("Could not create socket\n"); // 创建一个Socket $connection = socket_connect($socket, $host, $port) or die("Could not connet server\n"); // 连接 socket_write($socket, "time") or die("Write failed\n"); // 数据传送 向服务器发送消息echo 'wait for data';while (($buffer = socket_read($socket, 1024))!=false) { echo("Data sent was: time\nResponse was:" . $buffer . "\n");} socket_close($socket);
如果将server端对client read操作换成循环内部读取,则client会一直处于 wait data状态。
有办法让server端循环读的情况下,读完后给client写数据吗
回复讨论(解决方案)
你这个循环没有错,但是一次数据发送完成就关闭socket连接了,没有循环的必要吧。
<?phpset_time_limit(0); $host = "127.0.0.1";$port = 12345; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n"); // 创建一个Socket $result = socket_bind($socket, $host, $port) or die("Could not bind tosocket\n"); //绑定Socket到端口 $result = socket_listen($socket) or die("Could not set up socket listener\n"); // 开始监听连接 $spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); // 处理通信//若换成循环接收数据,客户端将一直处理等待接收状态$input = socket_read($spawn, 1024) or die("Could not read data\n"); while (( $data = socket_read($spawn, 1024)) != false) { $input .= $data;echo 'input:', strlen($input), "\n"; $output = date("Y-m-d H:i:s"). "\n"; //处理客户端输入并返回结果 echo "output:", $output, "\n"; // 数据传送 向客户端写入返回结果socket_write($spawn, $output, strlen($output)) or die("Could not write output\n"); }// 关闭socketssocket_close($spawn);socket_close($socket);
<?phpset_time_limit(0); $host = "127.0.0.1";$port = 12345; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n"); // 创建一个Socket $result = socket_bind($socket, $host, $port) or die("Could not bind tosocket\n"); //绑定Socket到端口 $result = socket_listen($socket) or die("Could not set up socket listener\n"); // 开始监听连接 $spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); // 处理通信//若换成循环接收数据,客户端将一直处理等待接收状态$input = socket_read($spawn, 1024) or die("Could not read data\n"); while (( $input = socket_read($spawn, 1024)) != false) { echo 'input:', strlen($input), "\n"; $output = date("Y-m-d H:i:s"). "\n"; //处理客户端输入并返回结果 echo "output:", $output, "\n"; // 数据传送 向客户端写入返回结果socket_write($spawn, $output, strlen($output)) or die("Could not write output\n"); }// 关闭socketssocket_close($spawn);socket_close($socket);
你这个循环没有错,但是一次数据发送完成就关闭socket连接了,没有循环的必要吧。
这个只是个demo,实际情况下,client发过来的数据不定长,所以只能循环接收
<?phpset_time_limit(0); $host = "127.0.0.1";$port = 12345; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n"); // 创建一个Socket $result = socket_bind($socket, $host, $port) or die("Could not bind tosocket\n"); //绑定Socket到端口 $result = socket_listen($socket) or die("Could not set up socket listener\n"); // 开始监听连接 $spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); // 处理通信//若换成循环接收数据,客户端将一直处理等待接收状态$input = socket_read($spawn, 1024) or die("Could not read data\n"); while (( $input = socket_read($spawn, 1024)) != false) { echo 'input:', strlen($input), "\n"; $output = date("Y-m-d H:i:s"). "\n"; //处理客户端输入并返回结果 echo "output:", $output, "\n"; // 数据传送 向客户端写入返回结果socket_write($spawn, $output, strlen($output)) or die("Could not write output\n"); }// 关闭socketssocket_close($spawn);socket_close($socket);
读循环里面确实不应该用PHP_NORMAL_READ这个选项
去掉PHP_NORMAL_READ这个选项也不能解决问题,有解决方法吗
while (true) { $msg = socket_accept ($socket); // 接受一个SOCKET if (!$msg) { echo "socket_accept() failed:".socket_strerror ($msg)."\n"; break; } while (true) { $command = strtoupper (trim (socket_read ($msg, 1024))); //等待客户端数据 if (!$command) break; //相关处理,比如直接回显 socket_write ($msg, $command, strlen ($command)); } socket_close ($msg); if ($command == "QUIT") //如果收到的是通讯结束 break;}socket_close ($socket); // 关闭SOCKET
<?phpset_time_limit(0); $host = "127.0.0.1";$port = 12345; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n"); // 创建一个Socket $result = socket_bind($socket, $host, $port) or die("Could not bind tosocket\n"); //绑定Socket到端口 $result = socket_listen($socket) or die("Could not set up socket listener\n"); // 开始监听连接 $spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); // 处理通信//若换成循环接收数据,客户端将一直处理等待接收状态$input = socket_read($spawn, 1024) or die("Could not read data\n"); while (( $input = socket_read($spawn, 1024)) != false) { echo 'input:', strlen($input), "\n"; $output = date("Y-m-d H:i:s"). "\n"; //处理客户端输入并返回结果 echo "output:", $output, "\n"; // 数据传送 向客户端写入返回结果socket_write($spawn, $output, strlen($output)) or die("Could not write output\n"); }// 关闭socketssocket_close($spawn);socket_close($socket);
读循环里面确实不应该用PHP_NORMAL_READ这个选项
去掉PHP_NORMAL_READ这个选项也不能解决问题,有解决方法吗
我都是用流函数实现的。
<?php/* * 不使用apache,cli模式 * 命令接收端 * 单用户,即单连接 *//** * 命令接收端Messenger * 单线程 */class SocketServer { protected $ip; protected $port; protected $webSocket; protected $users; protected $userIndex = 0; protected $message; public function __construct($ip = "127.0.0.1", $port = 12345) { $this->ip = $ip; $this->port = $port; // self::init(); // $this->createServer(); $this->log('listenning user...'); $this->listenningUser(); } protected function createServer() { $errno; $errstr; $this->webSocket = stream_socket_server("tcp://" . $this->ip . ':' . $this->port, $errno, $errstr); if (!$this->webSocket) { self::log("$errstr ($errno)"); exit(); } $this->log('server ok .'); } protected function listenningUser() { while (true) { $this->userIndex++; $user = $this->users[$this->userIndex] = stream_socket_accept($this->webSocket, 9999999999); // if (is_resource($this->users[$this->userIndex - 1])) { $u = $this->users[$this->userIndex - 1]; $u->close(); $u = NULL; unset($this->users[$this->userIndex - 1]); } // $this->log('连入新用户'); $this->listenningMessage(); } } protected function listenningMessage() { while (is_resource($this->users[$this->userIndex])) { $this->message = stream_socket_recvfrom($this->users[$this->userIndex], 10270000); if (!$this->message) { $this->closeUser(); break; } $this->messageOperate(); } } function messageOperate() { $this->log("收到消息:"); $this->log($this->message); //mb_strstr($haystack, $needle, $before_needle, $encoding) $this->sendMessage('done'); } function sendMessage($msg) { if($msg===''){ return -1; } return stream_socket_sendto($this->users[$this->userIndex], $msg); } public function closeUser() { if (!is_resource($this->users[$this->userIndex])) return FALSE; @stream_socket_shutdown($this->users[$this->userIndex], STREAM_SHUT_RDWR); @fclose($this->users[$this->userIndex]); $this->log("用户连接断开."); return TRUE; } public function shutdown() { stream_socket_shutdown($this->webSocket, STREAM_SHUT_RDWR); fclose($this->webSocket); } protected static function init() { error_reporting(E_ALL ^ E_NOTICE); set_time_limit(0); ob_implicit_flush(); date_default_timezone_set('Asia/Shanghai'); ignore_user_abort(TRUE); mb_internal_encoding('gbk'); } protected static function log($message) { echo "\r\n" . $message . "\r\n"; }}$server = new SocketServer();
<?php/* * 不使用apache,cli模式 * 客户端 */class SocketClient { protected $client; protected $message; public function __construct($domain,$port) { $this->init(); $this->client = stream_socket_client("tcp://$domain:$port", $errno, $errstr, 300000); if (!$this->client) { $this->log("$errstr ($errno)"); return FALSE; } $this->log('client ok'); } protected static function init() { error_reporting(E_ALL ^ E_NOTICE); //error_reporting(0); set_time_limit(0); ob_implicit_flush(); date_default_timezone_set('Asia/Shanghai'); ignore_user_abort(TRUE); mb_internal_encoding('gbk'); } public function sendMessage($msg) { if ($msg === '') { return -1; } try { stream_socket_sendto($this->client, $msg); } catch (Exception $exc) { //$this->log($exc->getTraceAsString()); } } public function getMessage() { $this->message = stream_socket_recvfrom($this->client, 10270000); //$this->log("收到消息:"); //$this->log($this->message); fwrite(STDOUT, $this->message . "\r\n"); } public function shutdown() { stream_socket_shutdown($this->client, STREAM_SHUT_RDWR); fclose($this->client); } public static function log($message) { echo "\r\n" . $message . "\r\n"; }}//$client = new SocketClient('127.0.0.1',12345);while (true) { $msg = fread(STDIN, 9999999); if (!trim($msg)) { continue; } $client->sendMessage($msg); $client->getMessage();}
while (true) { $msg = socket_accept ($socket); // 接受一个SOCKET if (!$msg) { echo "socket_accept() failed:".socket_strerror ($msg)."\n"; break; } while (true) { $command = strtoupper (trim (socket_read ($msg, 1024))); //等待客户端数据 if (!$command) break; //相关处理,比如直接回显 socket_write ($msg, $command, strlen ($command)); } socket_close ($msg); if ($command == "QUIT") //如果收到的是通讯结束 break;}socket_close ($socket); // 关闭SOCKET
版主好
这里我需要读取完client放的数据分析后才能write回client端,你想让client那边发送quit命令结束socket,这个在线上环境不能实现。还有更好的办法吗?多谢各位!!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

PHP是一种广泛应用于服务器端的脚本语言,特别适合web开发。1.PHP可以嵌入HTML,处理HTTP请求和响应,支持多种数据库。2.PHP用于生成动态网页内容,处理表单数据,访问数据库等,具有强大的社区支持和开源资源。3.PHP是解释型语言,执行过程包括词法分析、语法分析、编译和执行。4.PHP可以与MySQL结合用于用户注册系统等高级应用。5.调试PHP时,可使用error_reporting()和var_dump()等函数。6.优化PHP代码可通过缓存机制、优化数据库查询和使用内置函数。7

在PHP中,应使用password_hash和password_verify函数实现安全的密码哈希处理,不应使用MD5或SHA1。1)password_hash生成包含盐值的哈希,增强安全性。2)password_verify验证密码,通过比较哈希值确保安全。3)MD5和SHA1易受攻击且缺乏盐值,不适合现代密码安全。

PHP和Python各有优势,选择依据项目需求。1.PHP适合web开发,尤其快速开发和维护网站。2.Python适用于数据科学、机器学习和人工智能,语法简洁,适合初学者。

PHP在电子商务、内容管理系统和API开发中广泛应用。1)电子商务:用于购物车功能和支付处理。2)内容管理系统:用于动态内容生成和用户管理。3)API开发:用于RESTfulAPI开发和API安全性。通过性能优化和最佳实践,PHP应用的效率和可维护性得以提升。

PHP类型提示提升代码质量和可读性。1)标量类型提示:自PHP7.0起,允许在函数参数中指定基本数据类型,如int、float等。2)返回类型提示:确保函数返回值类型的一致性。3)联合类型提示:自PHP8.0起,允许在函数参数或返回值中指定多个类型。4)可空类型提示:允许包含null值,处理可能返回空值的函数。

PHP仍然具有活力,其在现代编程领域中依然占据重要地位。1)PHP的简单易学和强大社区支持使其在Web开发中广泛应用;2)其灵活性和稳定性使其在处理Web表单、数据库操作和文件处理等方面表现出色;3)PHP不断进化和优化,适用于初学者和经验丰富的开发者。

PHP适合web开发,特别是在快速开发和处理动态内容方面表现出色,但不擅长数据科学和企业级应用。与Python相比,PHP在web开发中更具优势,但在数据科学领域不如Python;与Java相比,PHP在企业级应用中表现较差,但在web开发中更灵活;与JavaScript相比,PHP在后端开发中更简洁,但在前端开发中不如JavaScript。

PHP主要是过程式编程,但也支持面向对象编程(OOP);Python支持多种范式,包括OOP、函数式和过程式编程。PHP适合web开发,Python适用于多种应用,如数据分析和机器学习。
