1

我需要帮助尝试将 VB6 代码转换为 PHP。我的 php 代码能够连接,但在超时发生之前一直保持连接。而且它不返回任何数据。

VB6代码:

Private Sub sckPing_Connect(index As Integer)
    Dim St As String, send As String
    St = Chr$(35)
    sckPing(index).SendData DoubleChar$(Len(St)) + Chr$(CheckSum(St) * 20 Mod 194) + Chr$(0) + St
End Sub

Private Sub sckPing_DataArrival(index As Integer, ByVal bytesTotal As Long)
    Dim Receive As String
    sckPing(index).GetData Receive, vbString, bytesTotal
    lstServers.List(index) = lstServers.List(index) + " (" + Receive + ")"
    sckPing(index).Close
End Sub

以下是我所拥有的,我能够创建校验和并打开与服务器的连接,但它似乎没有返回任何内容并且超时时间很长。

Function CheckSum($st)
{
For($a="1"; $a<strlen($st); $a=$a+1)
{
$B = $B + StrLen($st,$a,1);
}
return $B;
}

Function sckPing($addr, $prt)
{
$getplayers = Chr(35) + Chr(CheckSum(Chr(35)) * 20 % 194) + Chr(0) + Chr(35);
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
$result = socket_connect($socket,$addr,$prt);
$buf='';
socket_write($socket, $getplayers, StrLen($getplayers));
if (false !== ($bytes = socket_recv($socket, $buf, 8192, 0))) {

    echo "Read $bytes bytes from socket_recv(). Closing socket...";
} else {
    echo "socket_recv() failed; reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
        socket_set_nonblock($this->_SOCK); 

        $error = NULL; 
        $attempts = 0; 
        $timeout *= 1000;  // adjust because we sleeping in 1 millisecond increments 
        $connected; 
        while (!($connected = socket_connect($this->_SOCK, $remote, $port+0)) && $attempts++ < $timeout) { 
            $error = socket_last_error(); 
            if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) { 
                $this->errstr = "Error Connecting Socket: ".socket_strerror($error); 
                socket_close($this->_SOCK); 
                return NULL; 
            } 
            usleep(1000); 
        } 

        if (!$connected) { 
            $this->errstr = "Error Connecting Socket: Connect Timed Out After $timeout seconds. ".socket_strerror(socket_last_error()); 
            socket_close($this->_SOCK); 
            return NULL; 
        } 

        socket_set_block($this->_SOCK); 
socket_close($socket);

echo $buf . "\n";
echo "OK.\n\n";
}

sckPing("127.0.0.1", 5750);

错误:socket_recv() 失败;原因:现有连接被远程主机强行关闭。

4

0 回答 0