Socket accept gives error when I add socket_set_nonblock

101 Views Asked by At

My code worked fine, but when I changed and added socket_set_nonblock($socket) socket_accept gave me error 11, here is my code

<?php
session_start();
require "checklogin.php";
error_reporting(0);
$user=$_SESSION["usr"];

set_time_limit(0);
ob_implicit_flush();
$host="127.0.0.1";
$port=11287;
$greeting="\nWelcome to my PHP server(listener)\nto quit type 'quit\nto shutdown the server type 'shutdown'.\n";

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Err: " . socket_last_error());
socket_bind($socket, $host, $port) or die("Err: " . socket_last_error());
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {}
$result = socket_listen($socket) or die("can't set up listener");
socket_set_nonblock($socket) or die("rip multiple: " . socket_last_error());
while (true) {
if ($spawn = socket_accept($socket) or die("err: can't accept - " . socket_last_error())) {
socket_write($spawn, $greeting, strlen($greeting));
}
do {

$input = socket_read($spawn, 1024, PHP_NORMAL_READ) or die("Could not read input\n");
socket_write($spawn, $user, strlen("needreload"));
echo $input . "<br>";



}
while (true);

socket_close($spawn);
}
socket_close($socket);
?>

Any help appreciated

1

There are 1 best solutions below

0
On

... but when I changed and added socket_set_nonblock($socket) socket_accept gave me error 11, ...

11 is EAGAIN / EWOULDBLOCK, meaning that the operation (accept) would block if the socket wasn't explicitly set to non-blocking. This is exactly the error which is expected when setting a socket to non-blocking and one has to deal with it by trying later again, ideally after checking with select that the file descriptor is ready for doing this operation. If you don't want this kind of error then don't set the socket to non-blocking.