Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/gemblue/phpwebsocket
Simple PHP Websocket Library / Server for Fun
https://github.com/gemblue/phpwebsocket
php-socket php-websocket socket-programming websocket
Last synced: about 2 months ago
JSON representation
Simple PHP Websocket Library / Server for Fun
- Host: GitHub
- URL: https://github.com/gemblue/phpwebsocket
- Owner: gemblue
- Created: 2020-05-12T07:32:05.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2020-05-28T05:08:23.000Z (over 4 years ago)
- Last Synced: 2024-07-13T20:38:28.093Z (6 months ago)
- Topics: php-socket, php-websocket, socket-programming, websocket
- Language: PHP
- Homepage:
- Size: 18.6 KB
- Stars: 17
- Watchers: 4
- Forks: 10
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# PHPWebsocket
Simple PHP Websocket Library / Server for Fun. Just making a wrapper from PHP Socket API. Modifying source code from
reference and making simple OOP for a clean code.## Dependency
PHP Socket Library
https://www.php.net/manual/en/book.sockets.php## Install
Create a exercise folder. Open it and run composer require.
```
composer require gemblue/php-websocket
```## Run Server
- Make server file executable
```
sudo chmod +x ./vendor/gemblue/php-websocket/bin/server
```- Run websocket server with port option
```
./vendor/gemblue/php-websocket/bin/server port:3000
```Then it will show success output like
```
Listening incoming request on port 3000 ..
```## Prepare client.
Create a HTML file for websocket client, for example `index.html` :
```html
Nama
Pesan
Send
function showMessage(messageHTML) {
$('#output').append(messageHTML);
}$(document).ready(function(){
var websocket = new WebSocket("ws://127.0.0.1:3000");
websocket.onopen = function(event) {
showMessage("<div class='text-success'>Berhasil masuk room ..</div>");
}
websocket.onmessage = function(event) {
var Data = JSON.parse(event.data);
showMessage("<div>"+Data.message+"</div>");
$('#message').val('');
};
websocket.onerror = function(event){
showMessage("<div>Problem due to some Error</div>");
};
websocket.onclose = function(event){
showMessage("<div>Connection Closed</div>");
};
$('#btn-send').on("click",function(event){
event.preventDefault();
var messageJSON = {
name: $('#name').val(),
message: $('#message').val()
};
websocket.send(JSON.stringify(messageJSON));
});
});```
Open `index.html` with your browser. Use 2 tab/browser for simulation. Output will be like this :
![Sample](https://i.ibb.co/PGgH8vy/screenshot-ibb-co-2020-05-14-19-17-38.png)
## Reference
- https://stackoverflow.com/questions/42955033/php-client-web-socket-to-send-messages/43121475
- https://phppot.com/php/simple-php-chat-using-websocket
- https://medium.com/@cn007b/super-simple-php-websocket-example-ea2cd5893575