Advertisement
Guest User

Untitled

a guest
Dec 20th, 2014
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. // server state functions
  2. function wsStartServer($host, $port) {
  3. global $wsRead, $wsClientCount, $wsClientIPCount;
  4. if (isset($wsRead[0])) return false;
  5.  
  6. if (!$wsRead[0] = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) {
  7. return false;
  8. }
  9. if (!socket_set_option($wsRead[0], SOL_SOCKET, SO_REUSEADDR, 1)) {
  10. socket_close($wsRead[0]);
  11. return false;
  12. }
  13. if (!socket_bind($wsRead[0], $host, $port)) {
  14. socket_close($wsRead[0]);
  15. return false;
  16. }
  17. if (!socket_listen($wsRead[0], 10)) {
  18. socket_close($wsRead[0]);
  19. return false;
  20. }
  21.  
  22. $write = array();
  23. $except = array();
  24.  
  25. $nextPingCheck = time() + 1;
  26. while (isset($wsRead[0])) {
  27. $changed = $wsRead;
  28. $result = socket_select($changed, $write, $except, 1);
  29.  
  30. if ($result === false) {
  31. socket_close($wsRead[0]);
  32. return false;
  33. }
  34. elseif ($result > 0) {
  35. foreach ($changed as $clientID => $socket) {
  36. if ($clientID != 0) {
  37. // client socket changed
  38. $buffer = '';
  39. $bytes = @socket_recv($socket, $buffer, 4096, 0);
  40.  
  41. if ($bytes === false) {
  42. // error on recv, remove client socket (will check to send close frame)
  43. wsSendClientClose($clientID, WS_STATUS_PROTOCOL_ERROR);
  44. }
  45. elseif ($bytes > 0) {
  46. // process handshake or frame(s)
  47. if (!wsProcessClient($clientID, $buffer, $bytes)) {
  48. wsSendClientClose($clientID, WS_STATUS_PROTOCOL_ERROR);
  49. }
  50. }
  51. else {
  52. // 0 bytes received from client, meaning the client closed the TCP connection
  53. wsRemoveClient($clientID);
  54. }
  55. }
  56. else {
  57. // listen socket changed
  58. $client = socket_accept($wsRead[0]);
  59. if ($client !== false) {
  60. // fetch client IP as integer
  61. $clientIP = '';
  62. $result = socket_getpeername($client, $clientIP);
  63. $result2 = socket_getpeername($client, $clientIP);
  64. $clientIP = ip2long($clientIP);
  65.  
  66.  
  67.  
  68. $clientIP2 = 'test';
  69.  
  70. if ($result !== false && $wsClientCount < WS_MAX_CLIENTS && (!isset($wsClientIPCount[$clientIP]) || $wsClientIPCount[$clientIP] < WS_MAX_CLIENTS_PER_IP)) {
  71. wsAddClient($client, $clientIP, $wsClientIPCount[$clientIP]);
  72. }
  73. else {
  74. socket_close($client);
  75. }
  76. }
  77. }
  78. }
  79. }
  80.  
  81. if (time() >= $nextPingCheck) {
  82. wsCheckIdleClients();
  83. $nextPingCheck = time() + 1;
  84. }
  85. }
  86.  
  87. return true; // returned when wsStopServer() is called
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement