forked from lukaszkujawa/php-multithreaded-socket-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.php
More file actions
62 lines (52 loc) · 1.32 KB
/
server.php
File metadata and controls
62 lines (52 loc) · 1.32 KB
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
<?php
/**
* Check dependencies
*/
if( ! extension_loaded('sockets' ) ) {
echo "This example requires sockets extension (http://www.php.net/manual/en/sockets.installation.php)\n";
exit(-1);
}
if( ! extension_loaded('pcntl' ) ) {
echo "This example requires PCNTL extension (http://www.php.net/manual/en/pcntl.installation.php)\n";
exit(-1);
}
/**
* Connection handler
*/
function onConnect( $client ) {
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// parent process
return;
}
$read = '';
printf( "[%s] Connected at port %d\n", $client->getAddress(), $client->getPort() );
while( true ) {
$read = $client->read();
if( $read != '' ) {
$client->send( '[' . date( DATE_RFC822 ) . '] ' . $read );
}
else {
break;
}
if( preg_replace( '/[^a-z]/', '', $read ) == 'exit' ) {
break;
}
if( $read === null ) {
printf( "[%s] Disconnected\n", $client->getAddress() );
return false;
}
else {
printf( "[%s] recieved: %s", $client->getAddress(), $read );
}
}
$client->close();
printf( "[%s] Disconnected\n", $client->getAddress() );
}
require "sock/SocketServer.php";
$server = new \Sock\SocketServer();
$server->init();
$server->setConnectionHandler( 'onConnect' );
$server->listen();