-
Notifications
You must be signed in to change notification settings - Fork 0
/
SocketServer.php
40 lines (36 loc) · 1.29 KB
/
SocketServer.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
<?php
// Create a server socket
$socket = socket_create(AF_INET , SOCK_STREAM, SOL_TCP);
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socket, 'localhost', 8080);
socket_listen($socket);
$clients = array($socket);
// manter a conexão do servidor ativa
while(true) {
// Check for new clients
$read = $clients;
$write = $except = null;
socket_select($read, $write, $except, 0, 200000);
foreach($read as $client) {
if ($client === $socket) { // Handle incoming connections
$new_socket = socket_accept($socket);
$clients[] = $new_socket;
} else { //Handle incoming message
$data = socket_read($client, 1024);
if($data === false) { // Handle sockets closeds
$index = array_search($client, $clients);
unset($clients[$index]);
socket_close($client);
continue;
}
$message = trim($data);
if(!empty($message)) { //Broadcast message to other clients
foreach($clients as $other_client) {
if($other_client !== $socket && $other_client !== $client) {
socket_write($other_client, $message);
}
}
}
}
}
}