Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace app\index\helper;
- use PHPSocketIO\Socket;
- class ChatHelper
- {
- private $socket = null;
- private $usernames = [];
- private $numUsers = 0;
- public function __construct()
- {
- }
- // when the client emits 'new message', this listens and executes
- public function newMessage($data)
- {
- // we tell the client to execute 'new message'
- $this->socket->broadcast->emit('new message', array(
- 'username'=> $this->socket->username,
- 'message'=> $data
- ));
- }
- // when the client emits 'add user', this listens and executes
- public function addUser($username)
- {
- // we store the username in the socket session for this client
- $this->socket->username = $username;
- // add the client's username to the global list
- $this->usernames[$username] = $username;
- ++$this->numUsers;
- $this->socket->addedUser = true;
- $this->socket->emit('login', array(
- 'this->numUsers' => $this->numUsers
- ));
- // echo globally (all clients) that a person has connected
- $this->socket->broadcast->emit('user joined', array(
- 'username' => $this->socket->username,
- 'this->numUsers' => $this->numUsers
- ));
- }
- // when the client emits 'typing', we broadcast it to others
- public function typing()
- {
- $this->socket->broadcast->emit('typing', array(
- 'username' => $this->socket->username
- ));
- }
- // when the client emits 'stop typing', we broadcast it to others
- public function stopTyping()
- {
- $this->socket->broadcast->emit('stop typing', array(
- 'username' => $this->socket->username
- ));
- }
- // when the user disconnects.. perform this
- public function disconnect()
- {
- // remove the username from global usernames list
- if($this->socket->addedUser) {
- unset($this->usernames[$this->socket->username]);
- --$this->numUsers;
- // echo globally that this client has left
- $this->socket->broadcast->emit('user left', array(
- 'username' => $this->socket->username,
- 'this->numUsers' => $this->numUsers
- ));
- }
- }
- public function setSocket(Socket $socket)
- {
- $this->socket = $socket;
- }
- }
Add Comment
Please, Sign In to add comment