I am using this server script to create a Websocket server (server.php). This works fine.
<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Ratchet\WebSocket\WsServerInterface;
require 'vendor/autoload.php';
require_once 'db.php';
class MyClass implements MessageComponentInterface, WsServerInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
$name = str_replace('/', '', $conn->httpRequest->getUri()->getPath());
$resourceId = $conn->resourceId;
$stmt = $db->prepare("INSERT INTO clients (id, resourceId, name) VALUES (null, :resourceId, :name)");
$stmt->bindParam(':resourceId', $resourceId, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->execute();
ConnectDB::closeConnection($db);
echo "Connected (" . $resourceId . ")\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$name = str_replace('/', '', $conn->httpRequest->getUri()->getPath());
$request = json_decode($msg);
if (json_last_error() === JSON_ERROR_NONE) {
require_once 'process.php';
$response = processRequest($msg);
if ($response !== false) {
$from->send($response);
}
} else {
$from->send('JSON error');
$ActionType = 'Connect';
}
echo "Incoming message - " $name "\n";
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "Closed\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
$conn->close();
}
}
$server = IoServer::factory(
new HttpServer(
new WsServer(
new MyClass()
)
),
8080
);
$server->run();
I am saving the ID of $resourceId = $conn->resourceId; to a database.
What I would like to do is have another php script, currently test.php that could send messages to the clients via Ratchet.
Here is test.php
<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Ratchet\WebSocket\WsServerInterface;
require 'vendor/autoload.php';
require_once 'db.php';
$to = 119; // hard-coded id, not using database yet
$msg = json_encode(array("test" => "test"));
class Sender implements MessageComponentInterface, ConnectionInterface {
public function send(ConnectionInterface $to, $msg) {
$client = $this->clients[$to];
$client->send($msg);
}
}
Sender::send($to, $msg);
Error:
Fatal error: Declaration of Sender::send() must be compatible with Ratchet\ConnectionInterface::send($data) in test.php on line 20
This does not work and I do not know if this is the correct approach. I don't want to reply to an incoming message (that currently works), rather ultimately send a message from a form at test.php.
The Ratchet examples (Hello world) basically use the server to relay the messages between clients. In my case, I only want the server to communicate back and forth to individual clients. Clients never talk to each other. Also, the form at test.php does not create a client, nor does it expect an answer.
Can someone steer me in the right direction to send messages directly to clients?
Related
I am new at Ratchet Websocket and currently working on a simple chat application by using Ratchet Websocket library. Using the directions on the socketo.me site, I am trying to make websockets work by using the Chat.php and Server.php provided in http://socketo.me/docs/hello-world. My goal is want to send json string and update the database in the table (update chat messages). However, fa
This is the Chat.php which is the class that implements the MessageComponentInterface.
Chat class
<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
I added a function, so that the messages are inserted into the database.
savemessage function
public function savemessage($data)
{
$this->connect = 'mysql:host=' . $this->db_host .
';dbname=' . $this->db_name;
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$this->db_handler = new PDO($this->connect, $this->db_user, $this->db_pass, $options);
} catch (PDOException $e) {
$this->error = $e->getMessage();
echo $this->error;
}
$query = "INSERT INTO chatrooms (id, uuid, msg, created_on) VALUES (default, :uuid, :msg, :created_on)";
$this->statement = $this->db_handler->prepare($query);
$type = PDO::PARAM_STR;
$this->statement->bindValue(':uuid', $data['uuid'],$type);
$this->statement->bindValue(':msg', $data['msg'],$type);
$this->statement->bindValue(':created_on', $data['created_on'],$type);
return ($this->statement->execute());
}
Chat class(edited section) The function of onMessage is edited, in order to insert the data.
......
$data = json_decode($msg, true);
if ($this->savemessage($data)) {
echo 'Saved message to DB';
} else {
echo 'Failed to save message';
}
$data['dt'] = date("d-m-Y h:i:s");
foreach ($this->clients as $client) {
/*
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}*/
if ($client !== $from) {
$client->send($data['msg']);
}
}
......
Screenshot of error
As you can see from the screenshot, the connection is successful. The json string is successfully sent. However, there is a fatal error on the prepare function.
This line of code
$this->statement = $this->db_handler->prepare($query);
I have tried to call this function from other classes.(Originally the save message function is from other classes. The entire project is in MVC structure, but the error is still the same.)
It would be greatly appreciated if anyone have any ideas about what the problem might be or how to fix it. Thanks!
I have a very simple websocket using PHP and Ratchet libraray.
When a user opens a specific page it sends the users id to my socket and it should update the status for that user (at the moment I'm just logging it in the console), like this:
<input type="hidden" value="'.$account_id.'" id="account_id">
<input type="hidden" value="trial" id="request_type">
<script>
$(document).ready(function(){
var conn = new WebSocket('ws://127.0.0.1:8080');
conn.onopen = function(e){
console.log("Connection Opened!");
var account_id = $("#account_id").val();
var request_type = $("#request_type").val();
var data = {account_id: account_id, request_type: request_type};
conn.send(JSON.stringify(data));
}
conn.onclose = function(e){
console.log("Connection Closed!");
}
conn.onmessage = function(e) {
var data = JSON.parse(e.data);
console.log(data);
};
conn.onerror = function(e){
var data = JSON.parse(e.data);
console.log(data);
}
})
</script>
Then my socket script is as follows:
set_time_limit(0);
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
require dirname(__DIR__) . '../vendor/autoload.php';
class socket implements MessageComponentInterface{
protected $clients;
public function __construct(){
$this->clients = new \SplObjectStorage;
echo 'Server Started.'.PHP_EOL;
}
public function onOpen(ConnectionInterface $socket){
$this->clients->attach($socket);
echo 'New connection '.$socket->resourceId.'!'.PHP_EOL;
}
public function onClose(ConnectionInterface $socket) {
$this->clients->detach($socket);
echo 'Connection '.$socket->resourceId.' has disconnected'.PHP_EOL;
}
public function onError(ConnectionInterface $socket, \Exception $e) {
echo 'An error has occurred: '.$e->getMessage().'!'.PHP_EOL;
$socket->close();
}
public function onMessage(ConnectionInterface $from, $json){
echo 'Connection '.$from->resourceId.' sent '.$json.PHP_EOL;
$data = json_decode($json, true);
$account_id = $data['account_id'];
$request_type = $data['request_type'];
try {
$conn = new PDO("mysql:host=".$db_host.";port:".$db_port.";dbname=".$db_name."", $db_user, $db_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo $e->getMessage();
}
foreach ($this->clients as $client) {
if ($from->resourceId == $client->resourceId) {
if($request_type == 'trial'){
// while(true){
$response_array= [];
$stmt = $conn->prepare("SELECT * FROM table WHERE account_id=:account_id AND last_status_change=now()");
$stmt->bindParam(':account_id', $account_id);
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $key=>$value) {
$response_array[$key] = $value;
}
if(!empty($response_array)){
foreach($response_array as $item){
$status = $item['status'];
}
$response = array(
'account_id' => $account_id,
'status' => $status
);
var_dump($response);
$client->send(json_encode($response));
}
// sleep(5);
// }
}
}
}
}
}
$server = IoServer::factory(
new HttpServer(
new WsServer(
new socket()
)
),
8080
);
$server->run();
As it stands it works as expected, but only gives the current status if the status changed at the time when the page was loaded and I will see the status in the console, as soon as I un-comment the while() loop to actually keep checking the status for updates, my socket will do the var_dump() of the result in the command line when there is a status change but nothing gets logged in the client.
I'm new to websockets, I had been doing long polling by having an interval in JS that was sending a fetch() to a PHP script that got the latest DB results but it wasn't very efficient and was causing issues when a large number of clients were active and constantly making requests to the file which was in turn slowing down the DB. So I'm not sure why the while() loop is affecting it like this or if I am even going about this the right way.
A while loop is not how it works. It will block stuff and infinitely and unnecessarily consume resources.
What you want is addPeriodicTimer().
Check periodically for clients that need updates.
Add to your bootstrapping something like this:
$reactEventLoop->addPeriodicTimer(5, function() use $messageHandler, $server {
// Fetch all changed clients at once and update their status
$clientsToUpdate = getUpdatedClients($server->app->clients);
foreach ($clientsToUpdate as $client) {
$client->send(json_encode($response));
}
});
This is much more lightweight than any other method, as you can
Fetch N clients status with a single prepared database query
Update only changed clients periodically
Not put your app in a blocking state
Other resources on Stackoverflow will help you to find the right spot:
How do I access the ratchet php periodic loop and client sending inside app?
Periodically sending messages to clients in Ratchet
replace this line if ($from->resourceId == $client->resourceId) { with if ($from == $client) { this change may look simple but in the example Chat class provided by php ratchet in order avoid sending the message to the sender they have a condition to send messages to clients except the sender, they compared like this if ($from == $client) { only not only an resourceId the entire object itself!
you should be using addPeriodicTimer from Ratchet, although you have to make $clients public in order to place the timer.
Maybe you can place it inside the class and still be private, but I am not sure if it could initiate a timer for every client.
Anyway as you can see, you can create another public function that will actually do the job in the periodic timer(just like while loop)
and then call it once the client is connected and multiple times inside the timerloop,
for that I created also a public account_ids to keep truck of the account ids
Give it a try and let me know
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
require dirname(__DIR__) . '../vendor/autoload.php';
class socket implements MessageComponentInterface{
public $clients;
public $account_ids;
public function __construct(){
$this->clients = new \SplObjectStorage;
echo 'Server Started.'.PHP_EOL;
}
public function onOpen(ConnectionInterface $socket){
$this->clients->attach($socket);
echo 'New connection '.$socket->resourceId.'!'.PHP_EOL;
}
public function onClose(ConnectionInterface $socket) {
$this->clients->detach($socket);
echo 'Connection '.$socket->resourceId.' has disconnected'.PHP_EOL;
}
public function onError(ConnectionInterface $socket, \Exception $e) {
echo 'An error has occurred: '.$e->getMessage().'!'.PHP_EOL;
$socket->close();
}
public function onMessage(ConnectionInterface $from, $json){
echo 'Connection '.$from->resourceId.' sent '.$json.PHP_EOL;
$data = json_decode($json, true);
$account_id = $data['account_id'];
$request_type = $data['request_type'];
foreach ( $this->clients as $client ) {
if ( $from->resourceId == $client->resourceId ) {
if( $request_type == 'trial'){
$this->account_ids[$client->resourceId] = $account_id;
$this->checkStatus($client, $account_id);
}
}
}
}
public function checkStatus($client, $account_id){
try {
$conn = new PDO("mysql:host=".$db_host.";port:".$db_port.";dbname=".$db_name."", $db_user, $db_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo $e->getMessage();
}
$response_array= [];
$stmt = $conn->prepare("SELECT * FROM table WHERE account_id=:account_id AND last_status_change=now()");
$stmt->bindParam(':account_id', $account_id);
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $key=>$value) {
$response_array[$key] = $value;
}
if ( !empty($response_array) ) {
foreach($response_array as $item){
$status = $item['status'];
}
$response = array(
'account_id' => $account_id,
'status' => $status
);
var_dump($response);
$client->send(json_encode($response));
}
}
}
$socket = new socket();
$server = IoServer::factory(
new HttpServer(
new WsServer(
$socket
)
),
8080
);
$server->loop->addPeriodicTimer(5, function () use ($socket) {
foreach($socket->clients as $client) {
echo "Connection ".$client->resourceId." check\n";
$socket->checkStatus($client, $socket->account_ids[$client->resourceId]);
}
});
$server->run();
I'm using Ratchet PHP to send messages to clients, and I'm using
$server->loop->addPeriodicTimer(1, function () use ($row, $server) {...
To send a message every second. I can echo the message and the MySQL query works, but I am unable to actually access the clients object in $server, I can get to $server->app, but then when I do ->clients after that, it tells me that $clients doesn't exist.
To clarify, this isn't a problem when I don't use new HttpServer(...) but, without it, the browser console says the websocket handshake isn't valid, so that isn't a good workaround.
I've used print_r($server) and have confirmed that the clients object is inside a _httpServer:protected item. If I can access this, I'd be able to send messages, I think.
The code for the actual server video-server.php:
<?php
include "../../include/db.info.php";
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use React\EventLoop\Factory;
use MyApp\Chat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
), 888
);
$pdo = new PDO("mysql:host=localhost;port=3306;dbname=erewhon", "root", "");
$getUsername = $pdo->prepare("SELECT * FROM messages WHERE id=201");
$getUsername->execute();
$row = $getUsername->fetch(PDO::FETCH_ASSOC);
$server->loop->addPeriodicTimer(1, function () use ($row, $server) {
/*foreach ($server->app->component->clients as $client) {
$client->send("hello client");
}*/
print_r($server->app);
});
$server->run();
?>
The code for the classes file, chat.php:
<?php
namespace MyApp;
header("Content-Type: application/json; charset=UTF-8");
//include "../../db.info.php";
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
public $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
echo "Congratulations! the server is now running\n";
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
//dont need this
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
?>
It seems that you can't get that data the way you want.
The HttpServer define a protected variable.
protected $_httpServer; //<--- protected, you can't read from outside.
public function __construct(HttpServerInterface $component) {
$this->_httpServer = $component;
$this->_reqParser = new HttpRequestParser;
}
But, you can pass a instance of Chat and keep track of it. It will point to the same memory address.
Make a try:
$chat = new Chat(); //<--- ADD THIS LINE
$server = IoServer::factory(
new HttpServer(
new WsServer(
$chat //<----- USE HERE
)
), 888
);
....
$server->loop->addPeriodicTimer(1, function () use ($row, $server, $chat) {
/*foreach ($server->app->component->clients as $client) {
$client->send("hello client");
}*/
print_r($server->app);
print_r($chat->clients); // <---- PRINT HERE TO GET THE INFO
});
I've got my original answer below just in case, but I'd like to highlight that the accepted answer is the correct method, just don't forget to pass it to use
I know I probably shouldn't have done this to work around my problem, but it resolved it, so it is sufficient:
I went to vendor\cboden\ratchet\src\Ratchet\Http and edited HttpServer.php, specifically the variable protected $_httpServer, and changed it to public $_httpServer, which I probably shouldn't have, but that resolved my problem.
I could access the clients item by doing $server->app->_httpServer->component->clients.
Thanks to Felippe Duarte for highlighting this attribute, I didn't think of that.
I trying to connect ratchet with mysql database but I get this erorr
I run mysql using xampp phpmyadmin and I used the code in connectToDB.php file before to send data from html form to sql row using php and that worked ok
and I tested the code in Chat.php file before I adding the sql lines and that was working good but after I added the connectToDB.php line in chat.php i get this error so where the proplem ?
the error
PHP Fatal error: Undefined class constant 'MYSQL_ATTR_INIT_COMMAND'
in htdocs/connectToDB.php on line 19
the connectToDB.php code
<?php
if(!session_id()) session_start();
/* $dbhost = 'localhost';
//$dbname = '1852132_ch';
//$dbuser = 'root';
//$dbpass = ''; */
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "";
// database connection
try{
$_db = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass, array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => true
));
}catch(Excepion $e){
die("ERROR : ".$e->getMessage());
}
?>
the Chat.php file code
<?php
namespace MyApp;
include('/opt/lampp/htdocs/ww/classes/user.php');
include('/opt/lampp/htdocs/ww/connectToDB.php');
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
$sql = $_db->query("UPDATE users SET userid= '1999' WHERE UserName='batman'");
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
In your php.ini file, you should have the following line (uncommented):
extension=php_pdo_mysql.dll on Windows
extension=php_pdo_mysql.so on Linux/Mac
Then restart apache and try your code
I have a php code that calls another php script to get new data for a cache "JSON string". Here is my current code what does the communication
if( ! isset($_COOKIE['ICWS_SESSION']) ){
throw new exception('Not Clocked In');
}
if( ! isset($_COOKIE['ICWS_STATION']) ){
throw new exception('Missing Station Name');
}
$url = \classes\Cipher::decrypt($_COOKIE['ICWS_SESSION']);
$attrebutes = array('test');
//configure the connection
$conf = new ICWS\Config\Config($url, $_COOKIE['ICWS_STATION']);
//create a new instance of icws
$icws = new ICWS\Connection($conf, $attrebutes);
if ( !$icws->isLogged() ){
throw new exception('Something Went Wrong when trying to login');
}
$messaging = new ICWS\Messaging($icws);
while(1){
$messaging->processMessages();
$myQueue = array();
$myQueue = array_merge( (array) $messaging->getCallsQueue(), (array) $messaging->getCurrentUserStatusQueue()) ;
echo json_encode($myQueue);
sleep(1);
}
Now, I want to add this code in a Ratchet PHP WebSocket to ensure 1 TCP connection is made to the server per users to handle this request.
Here is my current websocket implementation.
<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
//open connection
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
//handle incoming messages from the client
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from === $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
//handle close connection
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
//handle errors
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
And here is how I start this WebSocket
<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require dirname(__DIR__) . '/../vendor/autoload.php';
require dirname(__DIR__) . '/icws/MyApp/Chat.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8010
);
$server->run();
Question
Where in my implementation I would add my loop after the connection is made?
Here is what I have tried
<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class icws implements MessageComponentInterface {
protected $clients;
protected $messaging;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
//open connection
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
if( ! isset($_COOKIE['ICWS_SESSION']) ){
throw new exception('Not Clocked In');
}
if( ! isset($_COOKIE['ICWS_STATION']) ){
throw new exception('Missing Station Name');
}
$url = \classes\Cipher::decrypt($_COOKIE['ICWS_SESSION']);
$attrebutes = array('test');
//configure the connection
$conf = new ICWS\Config\Config($url, $_COOKIE['ICWS_STATION']);
//create a new instance of icws
$icws = new ICWS\Connection($conf, $attrebutes);
if ( !$icws->isLogged() ){
throw new exception('Something Went Wrong when trying to login');
}
$this->messaging = new ICWS\Messaging($icws);
}
//handle incoming messages from the client
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from === $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
//handle close connection
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
//handle errors
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}