如何设置套接字时间限制? http://pastebin.com/0q3NeLAX
我尝试过socket_time_limit和其他人,但没有帮助。
我希望如果socket没有收到任何信息,它将在X秒后关闭。
function QueryMinecraft( $IP, $Port = 25565 )
{
$Socket = Socket_Create( AF_INET, SOCK_STREAM, SOL_TCP );
if( $Socket === FALSE || @Socket_Connect( $Socket, $IP, (int)$Port ) === FALSE )
{
return FALSE;
}
Socket_Send( $Socket, "\xFE", 1, 0 );
$Len = Socket_Recv( $Socket, $Data, 256, 0 );
Socket_Close( $Socket );
if( $Len < 4 || $Data[ 0 ] != "\xFF" )
{
return FALSE;
}
$Data = SubStr( $Data, 3 );
$Data = iconv( 'UTF-16BE', 'UTF-8', $Data );
$Data = Explode( "\xA7", $Data );
return Array(
'HostName' => SubStr( $Data[ 0 ], 0, -1 ),
'Players' => isset( $Data[ 1 ] ) ? IntVal( $Data[ 1 ] ) : 0,
'MaxPlayers' => isset( $Data[ 2 ] ) ? IntVal( $Data[ 2 ] ) : 0
);
}
答案 0 :(得分:0)
我不会为此使用套接字扩展,我只将其用于使用fsockopen()
无法完成的高级套接字操作。原因是套接字扩展并不总是可用,而fsockopen()
通常是。
以下是我用数据接收超时编写代码的方法:
function QueryMinecraft( $IP, $Port = 25565 )
{
// Seconds to wait for a successful connection
$connectTimeout = 5;
// Seconds to wait for data
$receiveTimeout = 5;
$Socket = fsockopen($IP, $port, $errNo, $errStr, $connectTimeout);
if( !$Socket || !stream_set_timeout( $Socket, $receiveTimeout ) )
{
return FALSE;
}
fwrite( $Socket, "\xFE" );
$Data = fread( $Socket, 256 );
fclose( $Socket );
if( strlen( $Data ) < 4 || $Data[ 0 ] != "\xFF" )
{
return FALSE;
}
$Data = SubStr( $Data, 3 );
$Data = iconv( 'UTF-16BE', 'UTF-8', $Data );
$Data = Explode( "\xA7", $Data );
return Array(
'HostName' => SubStr( $Data[ 0 ], 0, -1 ),
'Players' => isset( $Data[ 1 ] ) ? IntVal( $Data[ 1 ] ) : 0,
'MaxPlayers' => isset( $Data[ 2 ] ) ? IntVal( $Data[ 2 ] ) : 0
);
}