Home >Backend Development >PHP Tutorial >socket通信 php作为客户端,C++作为服务端通信有关问题。

socket通信 php作为客户端,C++作为服务端通信有关问题。

WBOY
WBOYOriginal
2016-06-13 12:16:011181browse

socket通信 php作为客户端,C++作为服务端通信问题。。。
最近想做一个如题这样的东西,现在php发送能成功,C++做出正确的相应:发送一段json字符串,但是C++发出的消息php怎么也收不到。。。不知道这是为什么。。请大家帮帮忙   难道是C++传给php的消息格式有什么问题?重点问题我感觉出在socket_read上。。但是没搞明白

<?php<br />error_reporting(E_ALL);<br />set_time_limit(0);<br />echo "<h2>TCP/IP Connection</h2>\n";<br /><br />$port = 6000;<br />$ip = "127.0.0.1";<br /><br /><br />$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);<br />if ($socket < 0) {<br />    echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";<br />}else {<br />    echo "OK.\n";<br />}<br /><br />echo "试图连接 '$ip' 端口 '$port'...\n";<br />$result = socket_connect($socket, $ip, $port);<br />if ($result < 0) {<br />    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";<br />}else {<br />    echo "连接OK\n";<br />}<br /><br />$in = 'r';<br />$out ='';<br /><br />	if(!socket_write($socket,$in,strlen($in))) {<br />		echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n";<br />	}else {<br />		<br />		echo "发送到服务器信息成功!\n";<br />		echo "发送的内容为:<font color='red'>$in</font> <br>";<br />		<br />	}<br /><br /><br />while($out = socket_read($socket,8192)) {<br />    //echo "接收服务器回传信息成功!\n";<br />	//$obj=json_decode($out); <br />    //echo "接受的内容为:",$out;<br />	echo $out;<br />	//echo $obj->0;<br />}<br /><br /><br />/*<br />if (false !== ($bytes = socket_recv($socket, $buf, 2048, MSG_WAITALL))) {<br />	echo 'aa'.$buf.'aa';<br />    echo "Read $bytes bytes from socket_recv(). Closing socket...";<br />} else {<br />    echo "socket_recv() failed; reason: " . socket_strerror(socket_last_error($socket)) . " ";<br />}<br />*/<br />echo "关闭SOCKET...\n";<br />socket_close($socket);<br />echo "关闭OK\n";<br />?>

------解决思路----------------------
那不就是 如果一直没有收到终止符 \0、\r、\n 则永远停在等待输入 的情况了
这说明服务端没有发送结束符(也就是没有遵守约定)
你也只能连接 socket_read($socket,1) 的结果了
其实读一块和读一个字节的效率是一样的(都是从输入缓冲区读的)

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