This is a Basic Chat Room Application. Used PHP websocket no used any kind of database (MySQL). This app using per to per communication to client browser in realtime
- first make folder 📁
Chat Room
- install websocket
composer require cboden/ratchet
- create a
src
folder 📁 - make a file
Chat.php
in src folder - you also read full Documentation of Ratchet WebSocket for php library.
<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
- create another folder 📂
bin
- make another file in bin folder 📂
Server.php
<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
$server->run();
- add a JavaScript file in index file.
var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log(e.data);
};
~bin/php Server.php
- open a browser (liked Chrome)
- pressed
F5
or open console. - write a code in your console
conn.send("Hello World");
enter hit. - share the link you chat room webapp your friends circle.
- let's chat with your friends
- run it
composer install
andcomposer update
- goto bin folder and run php cli
php Server.php
- goto you root folder run it
php -S localhost:8000
- Open chrome browser type this url http://localhost:8000
- share the this link 🔗 your friends and chating with your friends.