首页 > 编程语言 >php网络编程tcp

php网络编程tcp

时间:2024-12-23 20:54:18浏览次数:4  
标签:swoole 编程 tcp server sk length message php recv

服务端:

<?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
*/

  

客户端:

<?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:

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版本的客户端稍有问题,日后再研究

标签:swoole,编程,tcp,server,sk,length,message,php,recv
From: https://www.cnblogs.com/xuxiaobo/p/18625006

相关文章

  • php网络编程swoole http
    服务端:<?phpuseSwoole\Http\Server;useSwoole\Http\Request;useSwoole\Http\Response;//创建HTTP服务器$server=newServer('127.0.0.1',9501);$server->on('start',function($server){//print_r($server);echo&qu......
  • php网络编程swoole websocket
    服务端:<?phpuseSwoole\WebSocket\Server;//创建HTTP服务器$server=newServer('127.0.0.1',8888,SWOOLE_PROCESS,SWOOLE_SOCK_TCP);$server->on('start',function($server){//print_r($server);echo"Swoolewebsock......
  • php网络编程swoole udp
    服务端:<?php$server=newSwoole\Server('127.0.0.1',9504,SWOOLE_PROCESS,SWOOLE_SOCK_UDP);$server->on('start',function($server){echo"UDPServerisstartedatudp://127.0.0.1:9504\n";});$server->......
  • 学霸带你游戏化解构 Java 面向对象编程核心
    面向对象编程OOP使得代码结构清晰,开发者能够通过对象化的方式组织代码,使得代码逻辑更易理解和扩展。游戏中的每个角色、物品、事件、状态等都可以通过类和对象来管理,减少了代码的重复性,并提高了代码的可维护性。灵活性与扩展性OOP提供了高度的灵活性和扩展性,使得游戏开发......
  • python网络编程之socketio
    服务端: importsocketioclassChatServer:def__init__(self):#创建Socket.IO服务器实例self.sio=socketio.Server(cors_allowed_origins='*')self.app=socketio.WSGIApp(self.sio)#注册事件处理self.sio.on('......
  • python网络编程之sse
    服务端: fromfastapiimportFastAPIfromfastapi.responsesimportStreamingResponsefromfastapi.middleware.corsimportCORSMiddlewareimporttimeapp=FastAPI()#允许所有来源的跨域请求app.add_middleware(CORSMiddleware,allow_origins=["*"],......
  • Qt编程快速入门(1)Qt结构简介
    Qt构成Qt(/ˈkjuːt/,发音同“cute”)是一个跨平台的C++应用程序开发框架。广泛用于开发GUI程序,这种情况下又被称为部件工具箱。也可用于开发非GUI程序,例如控制台工具和服务器。-摘自维基百科Qt可以在多个平台编译运行,包括Windows、Linux、MacOS,其运行时的表现取决于操作系统的U......
  • python网络编程之websocket
    服务端: importasyncioimportwebsockets#保存已连接的客户端列表connected_clients=set()asyncdefhandle_websocket(websocket):#将新的客户端添加到已连接客户端列表remote_address=websocket.remote_addressconnected_clients.add(websocke......
  • python网络编程之tcp
    服务端: importsocketimportstructsk=socket.socket()sk.bind(('127.0.0.1',9501))#申请操作系统的资源sk.listen()whileTrue:#print(f'sk:{sk}')#conn里存储的是一个客户端和服务端的连接信息conn,adder=sk.accept()#能够和多个客户端......
  • python网络编程之udp
    服务端: importsocketsk=socket.socket(type=socket.SOCK_DGRAM)#表示一个udp协议sk.bind(('127.0.0.1',9504))#服务端不能先发送消息,因为服务端不知道客户端的ipwhileTrue:msg,addr=sk.recvfrom(1024)print(f"接收到客户端数据:{msg.decode('utf-8......