我有简单的tcp套接字。我必须从终端阅读消息。终端在消息中发送空字节。当我使用fgets()获取消息时,我得到了它,但是它不完整,它没有空字节,所以我无法解析它。我应该使用什么功能?
class ServerController extends Controller
{
public $connects = array();
public function startServer()
{
$fp = fopen('lock.txt', 'w');
flock($fp, LOCK_EX);
fwrite($fp, "Server started!!! \n");
flock($fp, LOCK_UN);
fclose($fp);
$socket = stream_socket_server("tcp://0.0.0.0:2215", $errno, $errstr);
if (!$socket) {
$this->writeLogs("Server stopped!!!\n");
die("$errstr ($errno)\n");
}
while (true) {
$read = $this->connects;
$read []= $socket;
$write = $except = null;
if (!stream_select($read, $write, $except, null)) {
break;
}
if (in_array($socket, $read)) {
//есть новое соединение
if (($connect = stream_socket_accept($socket, -1))) {
$this->writeLogs("New connect: ".$connect. "\n");
$this->connects[] = $connect;
$this->onOpen($connect);
}
unset($read[ array_search($socket, $read) ]);
}
foreach($read as $connect) {
$data = fgets($connect);
if (!$data) {
fclose($connect);
unset($this->connects[ array_search($connect, $this->connects) ]);
$this->onClose($connect);
continue;
}
$this->onMessage($connect, $data);
}
}
}
public function onOpen($connect) {
$exists_row = Lock::where('resource_id', $connect)->first();
if (!$exists_row) {
Lock::create([
'resource_id'=>$connect
]);
}
}
public function onClose($connect) {
Lock::where('resource_id', $connect)->delete();
}
public function onMessage($connect, $data) {
$this->writeLogs("Message sent by terminal: \n" . $data . "\n");
$protocol = new ConcoxProtocol($data, $connect);
$this->writeLogs("Response sent by server: \n".$protocol->response."\n");
fwrite($connect,$protocol->response);
}
public function sendMessage(Lock $lock, $command)
{
$command = new ServerCommand($command, $lock);
$this->writeLogs("Command sent by server : \n" . $command->response . "\n");
fwrite($this->connects[array_search($lock->resource_id, $this->connects)], $command->response);
}
public function writeLogs($str)
{
$fp = fopen('lock.txt', 'a');
flock($fp, LOCK_EX);
fwrite($fp, $str);
flock($fp, LOCK_UN);
fclose($fp);
}
}