下面加粗部分能实现接收超时100ms,避免socket接收永远block问题。
<?php
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
const SOCKET_SERV_HOST = "localhost";
const SOCKET_SERV_PORT = 1234;
class RCSocket{
private $socket;
private $host=SOCKET_SERV_HOST;
private $port=SOCKET_SERV_PORT;
public function __set($name,$value){
$this->$name=$value;
}
public function __construct($host=SOCKET_SERV_HOST,$port=SOCKET_SERV_PORT){
$this->host=$host;
$this->port=$port;
$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if(!$this->socket){
echo "socket_create() failed: " . socket_strerror(socket_last_error());
exit('Create socket failed!');
}
// set no data read timeout
socket_set_option($this->socket, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>0,"usec"=>100000));
$result = socket_connect($this->socket,$this->host,$this->port);
if(!$result){
echo "socket_connect() failed: " . socket_strerror(socket_last_error($this->socket));
exit('Connect to socket failed!');
}
//socket_set_nonblock($this->socket);
}
public function __desctruct(){
socket_close($this->socket);
}
public function send($data){
$result=socket_write($this->socket,$data);
if(!$result){
exit('Sent data to socket failed!');
}
}
public function recv($cnt){
return socket_read($this->socket, $cnt);
}
}
?>