1. Go to this page and download the library: Download naivic/oswserver library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
naivic / oswserver example snippets
namespace Grpc\Interconnect;
use OpenSwoole\GRPC;
class HostService implements HostInterface
{
public function Message(GRPC\ContextInterface $ctx, MessageRequest $request): MessageResponse
{
// Log the request
$ip = $ctx->getValue( \OpenSwoole\Http\Request::class )->server["remote_addr"];
\OpenSwoole\Util::LOG( \OpenSwoole\Constant::LOG_INFO, "Received GRPC Message from $ip, contains ".var_export($request->getMessage(), true) );
// Get instance of main server class
$serv = $ctx->getValue( 'WORKER_CONTEXT' )->getValue( \MyServer::class );
// Send message to client via websocket connection
[$success, $msg] = $serv->sendMsgToClient( "msg", $request->getName(), $request->getMessage(), $ip, null );
// Reply to gRPC peer
$message = new \Grpc\Interconnect\MessageResponse();
$message->setMessage( $msg );
$message->setSuccess( $success );
return $message;
}
}
class MyServer extends \Naivic\OswServer {
// Our gRPC port, as well as the gRPC peer port we will be sending our requests to
const PORT_GRPC = 9501;
}
class MyServer extends \Naivic\OswServer {
...
public $peer = null;
public function onStart( \OpenSwoole\HTTP\Server $server ) {
// Get gRPC peer IP from environment variable
$this->peer = $_ENV["PEER"];
\OpenSwoole\Util::LOG( \OpenSwoole\Constant::LOG_INFO, "Server starts with peer {$this->peer}" );
// Call parent class to provide standard initialization (mandatory)
parent::onStart( $server );
}
}
class MyServer extends \Naivic\OswServer {
...
public function sendMsgToClient( $type, $name, $text, $ip, $skip ) {
$sent = 0;
foreach( $this->server->connections as $conn ) {
if( $conn !== $skip ) {
if( $this->server->isEstablished($conn) ) {
if( $this->server->push( $conn, json_encode([ "type" => $type, "name" => $name, "text" => $text]) ) ) {
$sent++;
$log = "Message type '$type' with text '$text' from {$ip} was sent to client connection {$conn}";
\OpenSwoole\Util::LOG( \OpenSwoole\Constant::LOG_INFO, $log );
} else {
\OpenSwoole\Util::LOG( \OpenSwoole\Constant::LOG_INFO, "Cannot push message to client connection {$conn}" );
}
}
}
}
if( $sent == 0 ) {
$log = "Message type '$type' with text '$text' from {$ip} was not sent to client, because connection was closed";
\OpenSwoole\Util::LOG( \OpenSwoole\Constant::LOG_INFO, $log );
return [false, $msg];
}
return [true, "The message has been sent to {$sent} client connection".($sent>1?'s':'')];
}
}