Yes, you can create and test WebSocket applications on your localhost using XAMPP, but it requires some additional setup since XAMPP primarily serves HTTP requests. Here’s how you can do it:
Install Required Libraries:
Set Up Your Project:
htdocs directory and create a new project folder.bashcomposer require cboden/ratchet
Create a WebSocket Server:
server.php:php<?php
require 'vendor/autoload.php';
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class MyWebSocket implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
$server = IoServer::factory(new HttpServer(new WsServer(new MyWebSocket())), 8080);
$server->run();
Run the WebSocket Server:
bashphp server.php
Create a Client to Test the WebSocket:
client.html) in the same project folder:html<!DOCTYPE html>
<html>
<head>
<title>WebSocket Test</title>
</head>
<body>
<h1>WebSocket Test</h1>
<input id="message" type="text" placeholder="Type a message">
<button id="send">Send</button>
<ul id="messages"></ul>
<script>
const conn = new WebSocket('ws://localhost:8080');
conn.onopen = () => {
console.log("Connection established!");
};
conn.onmessage = (event) => {
const messages = document.getElementById('messages');
const message = document.createElement('li');
message.textContent = event.data;
messages.appendChild(message);
};
document.getElementById('send').onclick = () => {
const messageInput = document.getElementById('message');
conn.send(messageInput.value);
messageInput.value = '';
};
</script>
</body>
</html>
Open the Client:
client.html in your web browser. You can open multiple tabs to see how messages are sent and received.Feel free to ask if you need further assistance!