2017-12-06 15:36:55 +00:00
|
|
|
<?php
|
|
|
|
|
2017-12-06 16:12:08 +00:00
|
|
|
namespace kwebsocket\core;
|
2017-12-06 15:36:55 +00:00
|
|
|
|
|
|
|
class wsinterop{
|
|
|
|
|
|
|
|
|
|
|
|
private $socket;
|
|
|
|
private $host;
|
|
|
|
private $port;
|
|
|
|
private $isOpened;
|
|
|
|
|
|
|
|
public function __construct(String $host, int $port){
|
|
|
|
|
|
|
|
$this->socket = socket_create(AF_INET, SOCK_STREAM, 0);
|
|
|
|
$this->isOpened = socket_connect($this->socket,$host,$port);
|
|
|
|
$this->host = $host;
|
|
|
|
$this->port = $port;
|
|
|
|
|
|
|
|
socket_set_block($this->socket);
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
public function send(array $data) : bool{
|
|
|
|
|
|
|
|
if( !$this->isOpened ) return false;
|
|
|
|
|
|
|
|
$toSend = json_encode($data);
|
|
|
|
$size = strlen($toSend);
|
|
|
|
|
|
|
|
socket_write($this->socket,pack('N',$size));
|
|
|
|
$success = socket_write($this->socket,$toSend);
|
|
|
|
|
|
|
|
return $success == $size;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function receive() : array{
|
2017-12-07 14:35:07 +00:00
|
|
|
$size = 0;
|
|
|
|
while($size == 0){
|
|
|
|
$size = unpack("N",socket_read($this->socket,4))[1];
|
|
|
|
}
|
2017-12-06 15:36:55 +00:00
|
|
|
$read = 0;
|
|
|
|
$data = "";
|
|
|
|
$tmp = "";
|
|
|
|
|
|
|
|
while($read != $size){
|
|
|
|
|
|
|
|
$remaining = ($size - $read);
|
|
|
|
$read += socket_recv($this->socket,$tmp,$remaining,MSG_DONTWAIT);
|
|
|
|
$data .= $tmp;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
return json_decode($data,true);
|
|
|
|
}
|
|
|
|
|
2017-12-07 14:35:07 +00:00
|
|
|
public function close(){
|
|
|
|
socket_shutdown($this->socket);
|
|
|
|
socket_close($this->socket);
|
|
|
|
}
|
|
|
|
|
2017-12-06 15:36:55 +00:00
|
|
|
}
|