php實現一個簡單的socket

deww發表於2021-06-07
//確保在連線客戶端時不會超時
set_time_limit(0);
//設定IP和埠號
$address = "127.0.0.1";
$port = 54321;
$socketServer = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("socket_create() fail:" . socket_strerror(socket_last_error()) . "/n");
//設定為阻塞模式
socket_set_block($socketServer) or die("socket_set_block() fail:" . socket_strerror(socket_last_error()) . "/n");
//繫結埠
$result = socket_bind($socketServer, $address, $port) or die("socket_bind() fail:" . socket_strerror(socket_last_error()) . "/n");
//開始監聽
$result = socket_listen($socketServer, 4) or die("socket_listen() fail:" . socket_strerror(socket_last_error()) . "/n");

do {
    //接收連線請求並返回一個子Socket來處理客戶端和伺服器間的資訊
    $sock = socket_accept($socketServer) or  die("socket_accept() failed: reason: " . socket_strerror(socket_last_error()) . "/n");
    while($sock){
        //讀取客戶端資料
        echo "Read client data \n";

        $length = socket_read($sock, 4);
        $length = unpack('i', $length);
        echo "length:$length[1]   \n";

        $request = socket_read($sock, $length[1]);
        echo "$request:$request   \n";

        //資料傳送 向客戶端寫入返回結果
        $msg = "this is response message \n";
        $msgLength = strlen($msg);
        $msgLength = pack('i', $msgLength);
        socket_write($sock, $msgLength);
        socket_write($sock, $msg, strlen($msg)) or die("socket_write() failed: reason: " . socket_strerror(socket_last_error()) ."/n");
        break;
    }

} while (true);
socket_close($socketServer);

php開發工程師

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章