0
我正在製作一個PHP套接字服務器,但無法讓我的服務器讀取套接字。你如何讓你的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().
這是爲什麼?套接字已成功創建,但在嘗試讀取潛在傳入數據時發生錯誤。
您必須調用'socket_accept()'返回連接到傳入連接的新套接字。 – Barmar
@Barmar如果我打電話,服務器會凍結。如果我調用set_non_block,它將返回false。我不希望服務器等待連接,只是被動地在tick上檢測到它們。 – captincrunch
使其非阻塞,並定期調用'socket_accept'。如果它返回false,則沒有連接要處理。當它返回一個資源時,你可以從中讀取。 – Barmar