你如何让你的PHP服务器读取你刚刚创建的套接字?

时间:2017-10-06 22:52:00

标签: php sockets

我正在制作一个PHP套接字服务器,但我无法让我的服务器读取套接字。

    $this->log("Creating socket (please wait)...");

    $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if(socket_bind($this->socket, "127.0.0.1", 8080) === false){
        $this->log("Failed to bind socket to port (8080)");
        exit();
    }
    socket_listen($this->socket, 5);

    if(!is_resource($this->socket)){
        $this->log("Socket isn't a resource. Something went wrong, exiting.");
        exit();
    }

    $this->log("Socket created, creating socket reader...");
    $this->socketReader = new SocketReader($this);

    $this->log("server started");

    //socket should be non-blocking
    socket_set_nonblock($this->getSocket());

    //called every 10000 microseconds to read socket (error line here)
    public function process(){
        $buffer = socket_read($this->getSocket(), 128);
        var_dump($buffer);,
    }

我得到的错误是:

`Warning: socket_read(): unable to read from socket [57]: Socket is not connected` when calling proccess().

这是为什么?套接字已成功创建,但在尝试读取潜在的传入数据时出错。

1 个答案:

答案 0 :(得分:0)

您需要调用socket_accept()为传入连接获取新套接字,然后从中读取。

//called every 10000 microseconds to read socket
public function process(){
    $connection = socket_accept($this->getSocket());
    if ($connection) {
        socket_set_nonblock($connection);
        $buffer = socket_read($connection, 128);
        var_dump($buffer);
        socket_close($connection);
    }
}