Guest User

Untitled

a guest
Jun 20th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. <?php
  2. namespace app\index\helper;
  3.  
  4. use PHPSocketIO\Socket;
  5.  
  6. class ChatHelper
  7. {
  8. private $socket = null;
  9. private $usernames = [];
  10. private $numUsers = 0;
  11.  
  12. public function __construct()
  13. {
  14. }
  15. // when the client emits 'new message', this listens and executes
  16. public function newMessage($data)
  17. {
  18. // we tell the client to execute 'new message'
  19. $this->socket->broadcast->emit('new message', array(
  20. 'username'=> $this->socket->username,
  21. 'message'=> $data
  22. ));
  23. }
  24.  
  25. // when the client emits 'add user', this listens and executes
  26. public function addUser($username)
  27. {
  28. // we store the username in the socket session for this client
  29. $this->socket->username = $username;
  30. // add the client's username to the global list
  31. $this->usernames[$username] = $username;
  32. ++$this->numUsers;
  33.  
  34. $this->socket->addedUser = true;
  35. $this->socket->emit('login', array(
  36. 'this->numUsers' => $this->numUsers
  37. ));
  38. // echo globally (all clients) that a person has connected
  39. $this->socket->broadcast->emit('user joined', array(
  40. 'username' => $this->socket->username,
  41. 'this->numUsers' => $this->numUsers
  42. ));
  43. }
  44.  
  45. // when the client emits 'typing', we broadcast it to others
  46. public function typing()
  47. {
  48. $this->socket->broadcast->emit('typing', array(
  49. 'username' => $this->socket->username
  50. ));
  51. }
  52.  
  53. // when the client emits 'stop typing', we broadcast it to others
  54. public function stopTyping()
  55. {
  56. $this->socket->broadcast->emit('stop typing', array(
  57. 'username' => $this->socket->username
  58. ));
  59. }
  60.  
  61. // when the user disconnects.. perform this
  62. public function disconnect()
  63. {
  64. // remove the username from global usernames list
  65. if($this->socket->addedUser) {
  66. unset($this->usernames[$this->socket->username]);
  67. --$this->numUsers;
  68.  
  69. // echo globally that this client has left
  70. $this->socket->broadcast->emit('user left', array(
  71. 'username' => $this->socket->username,
  72. 'this->numUsers' => $this->numUsers
  73. ));
  74. }
  75. }
  76.  
  77. public function setSocket(Socket $socket)
  78. {
  79. $this->socket = $socket;
  80. }
  81. }
Add Comment
Please, Sign In to add comment