2

我用 php 编写了一个使用套接字的应用程序。突然需要在windows上运行它,在此之前它只在linux上没有问题。

目前的问题在于socket_recv使用的功能,如$bytes = @socket_recv($socket, $data, 2048, MSG_DONTWAIT);. 首先在窗户上没有任何MSG_DONTWAIT常数,因为我对此感到不解。我找到了一个小修复,例如:

if (!defined('MSG_DONTWAIT'))
   define('MSG_DONTWAIT', 0x40);

然后它说:

Warning: socket_recv(): unable to read from socket [0]: The operation completed
successfully.

之后我决定问在 Windows 和 Linux 上使用套接字可能有什么不同吗?

4

1 回答 1

0

我相信在 Windows 中创建套接字与在 linux 中创建套接字时有所不同。

尝试这样的事情:

<?php

// Init
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
$address = '127.0.0.1';
$port = 10000;

// On Windows we need to use AF_INET
$domain = (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' ? AF_INET : AF_UNIX);

// Create socket
if (($sock = socket_create($domain, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

// Bind socket to port
if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

// start listening
if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
do {
    if (($msgsock = socket_accept($sock)) === false) {
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        break;
    }
    /* Send instructions. */
    $msg = "\nWelcome to the PHP Test Server. \n" .
        "To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
    socket_write($msgsock, $msg, strlen($msg));

    do {
        if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
            echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
            break 2;
        }
        if (!$buf = trim($buf)) {
            continue;
        }
        if ($buf == 'quit') {
            break;
        }
        if ($buf == 'shutdown') {
            socket_close($msgsock);
            break 2;
        }
        $talkback = "PHP: You said '$buf'.\n";
        socket_write($msgsock, $talkback, strlen($talkback));
        echo "$buf\n";
    } while (true);
    socket_close($msgsock);
} while (true);

socket_close($sock);

?>
于 2013-11-08T13:32:53.263 回答