This project provides a simple WebSocket server implemented in PHP, along with a basic JavaScript client. It demonstrates real-time bidirectional communication using PHP sockets and the WebSocket API in JavaScript.
- WebSocket server in PHP
- WebSocket client in JavaScript
- Supports multiple client connections
- Implements WebSocket handshake
- Encodes and decodes WebSocket frames
- Broadcasts messages to all connected clients
- PHP 7.4+ (with socket extension enabled)
- A web browser with WebSocket support (e.g., Chrome, Firefox, Edge)
- Clone the repository or download the ZIP file:
git clone https://github.com/drupalerSV/websocket-with-php-sockets.git php-websocket cd php-websocket
- Start the WebSocket server:
php socket2.php
- Open
client.php
in a browser to test the WebSocket connection.
To start the WebSocket server, run the following command:
php socket2.php
The server will start listening on ws://127.0.0.1:8000
.
- Open
client.php
in a browser. - It will establish a WebSocket connection to the server.
- You can send messages using the input field.
- Messages from the server will appear in the chat window.
If you want to integrate the WebSocket client into another project, you can use the following JavaScript snippet:
const socket = new WebSocket("ws://127.0.0.1:8000");
socket.onopen = () => {
console.log("Connected to WebSocket server");
socket.send("Hello Server!");
};
socket.onmessage = (event) => {
console.log("Message from server:", event.data);
};
socket.onclose = () => {
console.log("Connection closed");
};
php-websocket/
│── client.php # WebSocket client UI
│── socket2.php # WebSocket server in PHP
│── index.php # Entry point (optional)
│── README.md # Documentation
│── images/ # Screenshots and illustrations
- If the server does not start, ensure the socket extension is enabled in
php.ini
:extension=sockets
- If the connection fails, check if port 8000 is open and not used by another application.
- Use browser developer tools (
F12 > Console
) to debug WebSocket messages.
This project is open-source and available under the MIT License.
Developed by Chance Nyasulu. Contributions are welcome!
If you'd like to improve this project, feel free to fork and submit a pull request.