-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket_server.php
132 lines (100 loc) · 3.25 KB
/
socket_server.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
<?php
require 'vendor/autoload.php';
use Workerman\Worker;
use PHPSocketIO\SocketIO;
use Utils\Message;
use Utils\UserList;
use function Utils\Helpers\isRealString;
$io = new SocketIO(2020);
$io->userList = new UserList;
$io->on('connection', function($socket) use($io){
echo "New user connected\n";
//Emit event to let the user know connection was succesfull.
//Which is completely unnecessary
$socket->emit('connect');
$socket->on('join', function($data, $callback) use($socket, $io){
if( !$io->userList->isValidUser($data) )
{
$callback([
'error' => 'No room name or user name provided'
]);
return;
}
$user = $io->userList->addUser($socket->id, $data['name'], $data['room']);
//Join a room
$socket->join($user->room);
//Send message to all users in the room except sender
$socket->to($user->room)->broadcast
->emit('newMessage', Message::fromAdmin($user->name, 'joined'));
//Send message to user
$socket->emit('welcome', Message::fromAdmin($user->name, 'greeting'));
//Send message to all users in the room
$io->in($user->room)
->emit('updateUserList', $io->userList->getRoomUsers($user->room));
$callback([
'success' => 'Welcome to the chat room'
]);
});
$socket->on('createMessage', function($data, $callback) use($socket, $io) {
$user = $io->userList->getUser($socket->id);
if($user === NULL)
{
$callback([
'error' => 'You must log in',
'noUser' => TRUE
]);
return;
}
if( !isRealString($data['text']) )
{
$callback([
'error' => 'Please send a valid message'
]);
return;
}
$io->in($user->room)
->emit('newMessage', Message::create($user->name, $data['text']));
$callback([
'success' => 'Message send succesfully'
]);
});
$socket->on('shareLocation', function($data, $callback) use($socket, $io) {
$user = $io->userList->getUser($socket->id);
if($user === NULL)
{
$callback([
'error' => 'You must log in',
'noUser' => TRUE
]);
return;
}
$io->in($user->room)
->emit(
'newLocationUrl',
Message::shareUserLocation(
$user->name,
$data['latitude'],
$data['longitude']
)
)
;
});
$socket->on('disconnect', function() use($socket, $io){
echo "User disconnected\n";
$user = $io->userList->getUser($socket->id);
if($user === NULL)
return;
$socket->leave($user->room);
$io->userList->removeUser($user->id);
$io->in($user->room)
->emit('newMessage', Message::fromAdmin($user->name, 'leave'));
$io->in($user->room)
->emit(
'updateUserList',
$io->userList->getRoomUsers($user->room)
)
;
});
});
Worker::runAll();
?>