fsockopen函数能够运用,首先要开启php.ini中的allow_url_open=on;
fsockopen是对socket客户端代码的封装,该函数中封装了socket_create,socket_connect。
服务器端代码:server.php
<?php<BR>error_reporting(E_ALL);<BR>set_time_limit(0);<BR>$address = '127.0.0.1';<BR>$port = 10008;<BR>//创建端口<BR>if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {<BR>echo "socket_create() failed:reason:" . socket_strerror(socket_last_error()) . "\n";<BR>}<BR>//绑定<BR>if (socket_bind($sock, $address, $port) === false) {<span style="color:transparent">本文来源gaodai#ma#com搞*!代#%^码$网!</span><strong>搞代gaodaima码</strong><BR>echo "socket_bind() failed :reason:" . socket_strerror(socket_last_error($sock)) . "\n";<BR>}<BR>//监听<BR>if (socket_listen($sock, 5) === false) {<BR>echo "socket_bind() failed :reason:" . socket_strerror(socket_last_error($sock)) . "\n";<BR>}<BR>while (true) {<BR>//得到一个链接<BR>if (($msgsock = socket_accept($sock)) === false) {<BR>echo "socket_accepty() failed :reason:".socket_strerror(socket_last_error($sock)) . "\n";<BR>break;<BR>}<BR>//welcome 发送到客户端<BR>$msg = "1.<font color='red'>server send:welcome</font><br />";<BR>socket_write($msgsock, $msg, strlen($msg)); //返回信息给客户端<BR>echo 'read client message\n';<BR>$buf = socket_read($msgsock, 8192); //获取客户端发送过来的信息<BR>$talkback = "2.received message:$buf\n";<BR>echo $talkback;<BR>if (false === socket_write($msgsock, $talkback, strlen($talkback))) { //返回信息给客户端<BR>echo "socket_write() failed reason:" . socket_strerror(socket_last_error($sock)) ."\n";<BR>} else {<BR>echo 'send success';<BR>}<BR>socket_close($msgsock);<BR>}<BR>socket_close($sock);<BR>
客户端代码:fsocket.php
<?php<BR>$fp = fsockopen("127.0.0.1", 10008, &$errno, &$errstr, 10);<BR>if (!$fp) {<BR>echo $errstr . " (". $errno . ")<br>n";<BR>} else {<BR>$in = "HEAD / http/1.1\r\n";<BR>$in .= "HOST: localhost \r\n";<BR>$in .= "Connection: close\r\n\r\n";<BR>fputs($fp, $in);<BR>while (!feof($fp)) {<BR>echo fgets($fp, 128);<BR>}<BR>fclose($fp);<BR>}<BR>