|
fsockopen是對socket客戶端代碼的封裝,該函數(shù)中封裝了socket_create,socket_connect。
服務(wù)器端代碼:server.php
復(fù)制代碼 代碼如下:
<?php
error_reporting(E_ALL);
set_time_limit(0);
$address = '127.0.0.1';
$port = 10008;
//創(chuàng)建端口
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
echo "socket_create() failed:reason:" . socket_strerror(socket_last_error()) . "/n";
}
//綁定
if (socket_bind($sock, $address, $port) === false) {
echo "socket_bind() failed :reason:" . socket_strerror(socket_last_error($sock)) . "/n";
}
//監(jiān)聽
if (socket_listen($sock, 5) === false) {
echo "socket_bind() failed :reason:" . socket_strerror(socket_last_error($sock)) . "/n";
}
while (true) {
//得到一個鏈接
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accepty() failed :reason:".socket_strerror(socket_last_error($sock)) . "/n";
break;
}
//welcome 發(fā)送到客戶端
$msg = "1.<font color='red'>server send:welcome</font><br/>";
socket_write($msgsock, $msg, strlen($msg)); //返回信息給客戶端
echo 'read client message/n';
$buf = socket_read($msgsock, 8192); //獲取客戶端發(fā)送過來的信息
$talkback = "2.received message:$buf/n";
echo $talkback;
if (false === socket_write($msgsock, $talkback, strlen($talkback))) { //返回信息給客戶端
echo "socket_write() failed reason:" . socket_strerror(socket_last_error($sock)) ."/n";
} else {
echo 'send success';
}
socket_close($msgsock);
}
socket_close($sock);
客戶端代碼:fsocket.php
復(fù)制代碼 代碼如下:
<?php
$fp = fsockopen("127.0.0.1", 10008, &$errno, &$errstr, 10);
if (!$fp) {
echo $errstr . " (". $errno . ")<br>n";
} else {
$in = "HEAD / http/1.1/r/n";
$in .= "HOST: localhost /r/n";
$in .= "Connection: close/r/n/r/n";
fputs($fp, $in);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
php技術(shù):基于php socket(fsockopen)的應(yīng)用實例分析,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。