/
Chat.php
83 lines (79 loc) · 3.2 KB
/
Chat.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
namespace App\Classes\Sockets;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$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');
$data=json_decode($msg);
if($data->status=='ping')
{
$data->status=='pong';
$from->send(json_encode($data));
}
if($data->status=='open')
{
$current_user=\App\ChatOnlineUser::where('username','=',$data->username)->first();
print_r(empty((array)$current_user));
if(!empty($current_user))
{
\App\ChatOnlineUser::where('username','=',$data->username)->delete();
}
$chat_user_data=array('username'=>$data->username,'name'=>$data->name,'connection_resource_id'=>$from->resourceId);
$online_users=\App\ChatOnlineUser::all();
$data->online_users=$online_users->toArray();
\App\ChatOnlineUser::create($chat_user_data);
$messages=\App\Message::all();
$data->content=$messages->toArray();
foreach ($this->clients as $client) {
//if ($from !== $client) {
$client->send(json_encode($data));
//}
}
}
if($data->status=='close')
{
foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send($msg);
}
}
}
if($data->status=='message')
{
$message_data=array('username'=>$data->username,'name'=>$data->name,'message_contents'=>$data->content);
\App\Message::create($message_data);
foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send($msg);
}
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
$disconnected_user=\App\ChatOnlineUser::where('connection_resource_id','=',$conn->resourceId)->first();
$data=array('status'=>'close','username'=>$disconnected_user->username,'name'=>$disconnected_user->name);
\App\ChatOnlineUser::where('connection_resource_id','=',$conn->resourceId)->delete();
echo "Connection {$conn->resourceId} has disconnected\n";
foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send(json_encode($data));
}
}
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}