Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // server state functions
- function wsStartServer($host, $port) {
- global $wsRead, $wsClientCount, $wsClientIPCount;
- if (isset($wsRead[0])) return false;
- if (!$wsRead[0] = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) {
- return false;
- }
- if (!socket_set_option($wsRead[0], SOL_SOCKET, SO_REUSEADDR, 1)) {
- socket_close($wsRead[0]);
- return false;
- }
- if (!socket_bind($wsRead[0], $host, $port)) {
- socket_close($wsRead[0]);
- return false;
- }
- if (!socket_listen($wsRead[0], 10)) {
- socket_close($wsRead[0]);
- return false;
- }
- $write = array();
- $except = array();
- $nextPingCheck = time() + 1;
- while (isset($wsRead[0])) {
- $changed = $wsRead;
- $result = socket_select($changed, $write, $except, 1);
- if ($result === false) {
- socket_close($wsRead[0]);
- return false;
- }
- elseif ($result > 0) {
- foreach ($changed as $clientID => $socket) {
- if ($clientID != 0) {
- // client socket changed
- $buffer = '';
- $bytes = @socket_recv($socket, $buffer, 4096, 0);
- if ($bytes === false) {
- // error on recv, remove client socket (will check to send close frame)
- wsSendClientClose($clientID, WS_STATUS_PROTOCOL_ERROR);
- }
- elseif ($bytes > 0) {
- // process handshake or frame(s)
- if (!wsProcessClient($clientID, $buffer, $bytes)) {
- wsSendClientClose($clientID, WS_STATUS_PROTOCOL_ERROR);
- }
- }
- else {
- // 0 bytes received from client, meaning the client closed the TCP connection
- wsRemoveClient($clientID);
- }
- }
- else {
- // listen socket changed
- $client = socket_accept($wsRead[0]);
- if ($client !== false) {
- // fetch client IP as integer
- $clientIP = '';
- $result = socket_getpeername($client, $clientIP);
- $result2 = socket_getpeername($client, $clientIP);
- $clientIP = ip2long($clientIP);
- $clientIP2 = 'test';
- if ($result !== false && $wsClientCount < WS_MAX_CLIENTS && (!isset($wsClientIPCount[$clientIP]) || $wsClientIPCount[$clientIP] < WS_MAX_CLIENTS_PER_IP)) {
- wsAddClient($client, $clientIP, $wsClientIPCount[$clientIP]);
- }
- else {
- socket_close($client);
- }
- }
- }
- }
- }
- if (time() >= $nextPingCheck) {
- wsCheckIdleClients();
- $nextPingCheck = time() + 1;
- }
- }
- return true; // returned when wsStopServer() is called
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement