今天试着写一个 PHP 与 C 语言通过socket通讯的程序,看过PHP手册,发现有好几种方式可以建立socket 客户端.
1、通过 fsockopen() 建立socket连接,然后用 用fputs() 发送消息,用 fgets() 接收消息。
2、通过 socket_create() 建立 socket 连接,然后用 socket_send() or socket_write() 发送消息,用 socket_recv() or socket_read() 发送消息。
很奇怪,我在手册上看到了这样一段话"本扩展模块是实验性的。该模块的行为,包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。" 看来 php4.0 socket通讯还不是完全稳定。
今天我写的客户端要与服务端做两次通讯,我用上面这个方法都写了一个客户端程序,发现当仅仅就一次通讯的时候,也就是PHP客户端发送一次消息,然后接收返回消息,就关闭连接。这两种方法都能正确快速的实现功能,但当做两次通讯时,却有明显的差别,第一种方法第一次通讯特别快就结束了,这个我可以通过服务端的输出看出来,但是第二次通讯要等上好几分钟才能结束,我试了好几次都这样,我不太清楚我的程序哪里出错了,还是这个方式连接就是有问题,但是第二种方法做这两次通讯却很快,正确!完成的非常的。
最后我根据 第二种情况写了一个 class
////////////////ile Description ////////////////////
//Class Name : socket
//Version: V1.0
//Functional Outline: create socket,and send message to server
//Revision history: 2004/12/15 First version created
// Current : 2004/12/15 Liu ongsheng
///////////////////////////////////////////
class socket{
var $socket; //socket 句柄
var $sendflag = ">>>";
var $recvflag = " var $response;
var $debug = 1;
function socket($hostname,$port){
$address = gethostbyname($hostname);
$this->socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
$result = socket_connect($this->socket,$address,$port);
if($this->debug == 1){
if ($result echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "
";
} else{
echo "connect OK.
";
}
}
}
function sendmsg($msg){
socket_write($this->socket,$msg,strlen($msg));
$result = socket_read($this->socket,100);
$this->response = $result;
if($this->debug == 1){
printf("%s $msg
",$this->sendflag);
printf("%s $result
",$this->recvflag);
}
return $result;
}
function close(){
socket_close($this->socket);
}
}

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
