start_io.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. use Workerman\Worker;
  3. use Workerman\WebServer;
  4. use Workerman\Autoloader;
  5. use PHPSocketIO\SocketIO;
  6. // composer autoload
  7. require_once join(DIRECTORY_SEPARATOR, array(__DIR__, "..", "..", "vendor", "autoload.php"));
  8. $io = new SocketIO(2020);
  9. $io->on('connection', function($socket){
  10. $socket->addedUser = false;
  11. // when the client emits 'new message', this listens and executes
  12. $socket->on('new message', function ($data)use($socket){
  13. // we tell the client to execute 'new message'
  14. $socket->broadcast->emit('new message', array(
  15. 'username'=> $socket->username,
  16. 'message'=> $data
  17. ));
  18. });
  19. // when the client emits 'add user', this listens and executes
  20. $socket->on('add user', function ($username) use($socket){
  21. if ($socket->addedUser)
  22. return;
  23. global $usernames, $numUsers;
  24. // we store the username in the socket session for this client
  25. $socket->username = $username;
  26. ++$numUsers;
  27. $socket->addedUser = true;
  28. $socket->emit('login', array(
  29. 'numUsers' => $numUsers
  30. ));
  31. // echo globally (all clients) that a person has connected
  32. $socket->broadcast->emit('user joined', array(
  33. 'username' => $socket->username,
  34. 'numUsers' => $numUsers
  35. ));
  36. });
  37. // when the client emits 'typing', we broadcast it to others
  38. $socket->on('typing', function () use($socket) {
  39. $socket->broadcast->emit('typing', array(
  40. 'username' => $socket->username
  41. ));
  42. });
  43. // when the client emits 'stop typing', we broadcast it to others
  44. $socket->on('stop typing', function () use($socket) {
  45. $socket->broadcast->emit('stop typing', array(
  46. 'username' => $socket->username
  47. ));
  48. });
  49. // when the user disconnects.. perform this
  50. $socket->on('disconnect', function () use($socket) {
  51. global $usernames, $numUsers;
  52. if($socket->addedUser) {
  53. --$numUsers;
  54. // echo globally that this client has left
  55. $socket->broadcast->emit('user left', array(
  56. 'username' => $socket->username,
  57. 'numUsers' => $numUsers
  58. ));
  59. }
  60. });
  61. });
  62. if (!defined('GLOBAL_START')) {
  63. Worker::runAll();
  64. }