我在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上使用套接字有什么不同吗?
答案 0 :(得分: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);
?>