php网络编程swoole tcp
服务端:
<?php $server = new Swoole\Server('127.0.0.1', 9501); $server->set([ 'worker_num' => 8, // worker进程数 cpu1-4倍 'max_request' => 10000, // 根据内存定义 https://wiki.swoole.com/#/server/setting // 'open_eof_check' => true, // 'package_eof' => "\r\n", 'open_length_check' => true, 'package_max_length' => 81920, 'package_length_type' => 'S', //see php pack() 'package_length_offset' => 0, 'package_body_offset' => 4, ]); $server->on('start', function ($server) { echo "TCP Server is started at tcp://127.0.0.1:9501\n"; }); $server->on('connect', function ($server, $fd){ echo "connection open: {$fd}\n"; }); $server->on('receive', function ($server, $fd, $reactor_id, $data) { echo "reactor_id:{$reactor_id}\n"; echo "接收到客户端数据:{$data}\n"; $message = '我收到你的消息了1'; $sendMessage = pack("I", strlen($message)) . $message; $server->send($fd, $sendMessage); $message = '我收到你的消息了2'; $sendMessage = pack("I", strlen($message)) . $message; $server->send($fd, $sendMessage); }); $server->on('close', function ($server, $fd) { echo "connection close: {$fd}\n"; }); $server->start(); /* 推荐观看:swoole PHP—swoole通往大神修炼之路:av77924246 手把手教你用swoole+websocket实现户外监控直播(总集篇):av79087951 教你用swoole开发网络游戏:av79264440 PHP高级技术手写swoole分布式框架:av78383962 PHP高级技术手写swoole分布式框架(二):av78632435 PHP高级技术手写swoole分布式框架(三):av78748923 PHP高级技术手写swoole分布式框架(框架优化):av78856427 PHP高级技术手写swoole分布式框架(分布式RPC):av79012272 用swoole实现消息推送:av79874641 swoole+docker+redis主从复制及读写分离av78781841 */
客户端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php $client = new Swoole\Client(SWOOLE_SOCK_TCP); if (! $client ->connect( '127.0.0.1' , 9501, -1)) { exit ( "connect failed. Error: {$client->errCode}\n" ); } $message = '测试一下,php客户端' ; $length = pack( "I" , strlen ( $message )); $client ->send( $length . $message ); $length = $client ->recv(4); $length = unpack( "I" , $length )[1]; echo "收到服务端回复:" . $client ->recv( $length ). "\n" ; $length = $client ->recv(4); $length = unpack( "I" , $length )[1]; echo "收到服务端回复:" . $client ->recv( $length ). "\n" ; $client ->close(); //https://www.runoob.com/php/func-misc-pack.html |
客户端python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import socket import struct sk = socket.socket() # 必须和server端的一致 sk.connect(( '127.0.0.1' , 9501 )) # 客户端 发送 消息给服务端 msg1 = '测试一下,python客户端' blen = struct.pack( 'I' , len (msg1.encode())) sk.send(blen) sk.send(msg1.encode( 'utf-8' )) length = sk.recv( 4 ) length = struct.unpack( 'I' , length)[ 0 ] msg = sk.recv(length) print (f "收到服务端回复:{msg.decode('utf-8')}" ) length = sk.recv( 4 ) length = struct.unpack( 'I' , length)[ 0 ] msg = sk.recv(length) print (f "收到服务端回复:{msg.decode('utf-8')}" ) sk.close() |
输出:
php版本的客户端稍有问题,日后再研究
本文来自博客园,作者:河北大学-徐小波,转载请注明原文链接:https://www.cnblogs.com/xuxiaobo/p/18625006

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步