main/build/kwebsocket/core/wsinterop.php

54 lines
1.0 KiB
PHP

<?php
namespace \kwebsocket\core;
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{
$size = unpack("N",socket_read($this->socket,4))[1];
$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);
}
}