//建立socket服務
$c=stream_socket_server("tcp://127.0.0.1:1100");
while(1)
{
if(is_resource($a=stream_socket_accept($c)))
{
//do something time-consuming
//擷取網路socket名稱
if(stream_socket_get_name($a,true)!==false)
{
fwrite($a,"regards form berlin");
}
}
}
//
//建立兩個無區別的socket資料流串連
$sockets=stream_socket_pair(stream_pf_unix,stream_sock_stream,stream_ipproto_ip);
//建立子進程並返回其pid
$pid=pcntl_fork();
if($pid==-1)
{
//如果沒有子進程
die('could not fork');
}
else if($pid)
{
/*父進程*/
fclose($sockets[0]);
fwrite($sockets[1], "child pid: $pidn");
echo fgets($sockets[1]);
fclose($sockets[1]);
}
else
{
/*子進程*/
fclose($sockets[1]);
fwrite($sockets[0], "message from childn");
echo fgets($sockets[0]);
fclose($sockets[0]);
}
//
/*開啟一個socket服務端*/
$server=stream_socket_server('tcp://127.0.0.1:1234');
/*接受一個串連*/
$socket=stream_socket_accept($server);
/*擷取資料*/
echo "received out-of-band:'".stream_socket_recvfrom($socket,1500,stream_oob)."'n";
/*使用peek擷取資料*/
echo "data:'".stream_socket_recvfrom($socket,1500,stream_peek)."'n";
/*正常擷取數*/
echo "data:'".stream_socket_recvfrom($socket,1500)."'n";
/*關閉socket*/
fclose($socket);
fclose($server);
//
/*開啟一個socket用戶端*/
$socket=stream_socket_client('tcp://127.0.0.1:1234');
/*發送正常資料*/
fwrite($socket,"normal data transmit.");
/*發送更多的資料*/
stream_socket_sendto($socket,"out of band data.",stream_oob);
/*關閉socket*/
fclose($socket);
//
//建立服務端
$socket=stream_socket_server("tcp://0.0.0.0:8000",$errno,$errstr);
//如果建立失敗
if(!$socket)
{
echo "$errstr ($errno)<br />n";
}
//如果建立成功
else
{
//接受串連
while($conn=stream_socket_accept($socket))
{
//寫入資料
fwrite($conn,'the local time is '.date('n/j/y g:i a')."n");
//關閉串連
fclose($conn);
}
//關閉socket
fclose($socket);
}