使用 Socket

1 篇文章 / 0 new
author
使用 Socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    $error = socket_last_error();
    $errormsg = socket_strerror($error);    
    die("Couldn't create socket: [$error] $errormsg");
    return NULL;
}
socket_set_block($socket);
 
$timeout = 0;
$error = NULL;
while (!($connected = @socket_connect($socket, '127.0.0.1', 2000)) && ($timeout < 10)) {
    $error = socket_last_error();
    if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
        socket_close($socket);
        $errormsg = socket_strerror($error);
        die("連線失敗[$error] : $errormsg");
        return NULL;
    }
    usleep(500);
    $timeout++;
}
$send = "123456\n";
echo "傳送請求:";
$sendLen = socket_write($socket, $send, strlen($send));
echo "OK($sendLen).\n";
 
echo "socket_recv 進行資料接收\n";
$buf = 'This is my buffer.';
if (false !== ($bytes = socket_recv($socket, $buf, 2048, MSG_WAITALL))) {
    echo "讀取 $bytes bytes, 資料:$buf";
} else {
    echo "socket_recv() 接收失敗:" . socket_strerror(socket_last_error($socket)) . "\n";
}
 
socket_close($socket);
Socket 函式說明
Free Web Hosting