Skip to content

Commit 4c94ef5

Browse files
committed
Changed demo example to slightly more complex chat example
1 parent a2d4676 commit 4c94ef5

File tree

4 files changed

+13
-7
lines changed

4 files changed

+13
-7
lines changed

examples/demo.html renamed to examples/chat.html

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,15 @@
2323
}
2424

2525
function init() {
26-
var host = "ws://localhost:12345/echo";
26+
var host = "ws://localhost:12345/chat";
2727
try {
2828
socket = createSocket(host);
2929
log('WebSocket - status ' + socket.readyState);
3030
socket.onopen = function(msg) {
3131
log("Welcome - status " + this.readyState);
3232
};
3333
socket.onmessage = function(msg) {
34-
log("Received (" + msg.data.length + " bytes): " + msg.data);
34+
log(msg.data);
3535
};
3636
socket.onclose = function(msg) {
3737
log("Disconnected - status " + this.readyState);
@@ -48,7 +48,6 @@
4848

4949
try {
5050
socket.send(msg);
51-
log('Sent (' + msg.length + " bytes): " + msg);
5251
} catch (ex) {
5352
log(ex);
5453
}

examples/demo.php renamed to examples/chat.php

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,18 @@
2222
*/
2323
class DemoEchoHandler extends WebSocketUriHandler {
2424

25+
public function onConnect(WebSocketConnectionInterface $user){
26+
foreach($this->getConnections() as $client){
27+
$client->sendString("User {$user->getId()} joined the chat: ");
28+
}
29+
}
2530

2631
public function onMessage(WebSocketConnectionInterface $user, WebSocketMessageInterface $msg) {
27-
$this->logger->notice("[ECHO] " . strlen($msg->getData()) . " bytes");
28-
// Echo
29-
$user->sendMessage($msg);
32+
$this->logger->notice("Broadcasting " . strlen($msg->getData()) . " bytes");
33+
34+
foreach($this->getConnections() as $client){
35+
$client->sendString("User {$user->getId()} said: ".$msg->getData());
36+
}
3037
}
3138
}
3239

@@ -40,7 +47,7 @@ public function onMessage(WebSocketConnectionInterface $user, WebSocketMessageIn
4047
// Create a WebSocket server and create a router which sends all user requesting /echo to the DemoEchoHandler above
4148
$server = new WebSocketServer("tcp://0.0.0.0:12345", $loop, $logger);
4249
$router = new \Devristo\Phpws\Server\UriHandler\ClientRouter($server, $logger);
43-
$router->addUriHandler('#^/echo$#i', new DemoEchoHandler($logger));
50+
$router->addUriHandler('#^/chat$#i', new DemoEchoHandler($logger));
4451

4552
// Bind the server
4653
$server->bind();
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)