search
HomeBackend DevelopmentPHP Tutorialcentos下php socket连接,该如何解决

centos下php socket连接
最近要做一个基于tcp/ip下的短连接
我们自己的代码使用的是php的socket连接,对方服务器,已经测试能够连接,并接收到对方传回来的数据;
现在要求我们自己也需要搭建一个socket服务器,要求对方也可以连接我们服务器,获取相关数据。

以前没有做个socket连接,刚刚接触
服务器也已经设置了一个端口好,可以telnet访问

看网络很多关于socket的php介绍,一些例子也使用了,服务器端的文件,总是不能被访问返回数据

有朋友做个这方面的吗?
帮忙一下
怎么写服务器端文件,怎么实时监听到该socket端口有socket请求,并返回数据个对方

谢谢了
------解决方案--------------------
是的,端口被打开了就不能复用
所以通讯时需要先打开一个周知的端口,一旦监听到该端口有信息时
就需要打开一个空闲端口,并将该端口通知对方,用于后续的通讯

服务方的主监听程序需要常驻内存,只能启动一次
通讯是通过子进程进行的

需要注意的是:php 适合做客户端,而不适合做服务端
可能以后更高的版本会有所改变,至少在php5.5也还是没有改变(虽然已经列入开发计划)

------解决方案--------------------
如果你需要xml进行通信的话,webservice就是最好的选择。你可以了解一下webservice,比如soap。你只要开放webservice对方调用就可以,而且对方可以是任何语言或程序。
------解决方案--------------------
楼主要的东西其实就是RPC,我有一个,你可以直接拿去用,
https://github.com/walkor/workerman

开发文档在:http://www.workerman.net/documentation
安装部署开发都非常方便。

如果有啥不明白,可以随时联系我

------解决方案--------------------

<br />//server.php<br />set_time_limit(0);<br />// Set up our socket<br />$commonProtocol = getprotobyname("tcp");<br />$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);<br />socket_bind($socket, '192.168.10.224', 50004);<br />socket_listen($socket,5);<br />// Initialize the buffer<br />$buffer = "";<br />while(true)<br />{<br />	$run=file_get_contents("./run.txt");<br />	if($run==0)break;<br />	// Accept any connections coming in on this socket<br />	<br />	$connection = socket_accept($socket);<br />	printf("Socket 链接中\r\n");<br />	// Check to see if there is anything in the buffer<br />	if($buffer != "")<br />	{<br />	   printf("写入开始 缓冲区内容发送..\r\n");<br />	   socket_write($connection, $buffer . "\r\n");<br />	   printf("写入结束 \r\n");<br />	}<br />	else<br />	{<br />	   printf("缓冲区无数据\r\n");<br />	}<br />	// Get the input   socket_read($connection, 1024)<br />	while($data = socket_read($connection, 4096))<br />	{<br />		if($run==0)break;<br />	   $buffer = $data;<br />	   //写入客户端数据<br />	   file_put_contents("./txt.txt", json_encode($data)."\n",FILE_APPEND);<br />	   socket_write($connection, "Information Received\r\n");<br />	   printf("读结束 缓冲区内容: " . $buffer . "\r\n");<br />	}<br />	socket_close($connection);<br />	printf("关闭 socket\r\n\r\n");<br />}<br /><br />//命令行里 输入:  php server.php<br /><br />//client.php 直接浏览器访问<br />$stime = microtime(true);<br />$fp = stream_socket_client("tcp://192.168.10.224:50004", $errno, $errstr, 30,STREAM_CLIENT_CONNECT <br><font color='#FF8000'>------解决方案--------------------</font><br> STREAM_CLIENT_PERSISTENT);<br />if (!$fp) {<br />    echo "$errstr ($errno)<br />\n";<br />} else {<br /> <br />    fwrite($fp,$msg,mb_strlen($msg));<br /> <br />    echo fread($fp, 4096)."\n";<br />    fclose($fp);<br />}<br /><br />$etime = microtime(true);<br /><br />echo "Time: " . ($etime - $stime) . "n";<br /><br /><br />//我目前杀掉占用端口太麻烦,直接用文件控制退出 。run.txt 文件存 0或1 <br />
 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

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

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

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.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

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

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

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

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

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

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

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

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

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.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool