walkor / walkor/workerman

Can you please tell me how the client code in php will look like?

Open
#892 5 comments 0 reactions 0 assignees View on GitHub
Dominant language
PHP
Stars
11.6k
Forks
2.2k
Avg merge
11h 30m
Merged PRs (30d)
3

Description

Can you please tell me how the client code in php will look like? The client must be able to send data to the server and receive data from other clients

my server
```
require_once __DIR__ . '/vendor/autoload.php';
use Workerman\Worker;

$users = [];

$ws_worker = new Worker("websocket://0.0.0.0:8000");

$ws_worker->onWorkerStart = function() use (&$users)
{
$inner_tcp_worker = new Worker("tcp://127.0.0.1:1234");

$inner_tcp_worker->onMessage = function($connection, $data) use (&$users) {
$data = json_decode($data);
var_dump($data);
foreach($users as $user_connection) {
if($user_connection->id !== $connection->id) {
$user_connection->send($data->message);
}
}
};

$inner_tcp_worker->listen();
};

$ws_worker->onMessage = function($connection, $data) use (&$users) {
$data = json_decode($data);
var_dump($data);
foreach($users as $user_connection) {
if($user_connection->id !== $connection->id) {
$user_connection->send($data->message);
}
}
};

$ws_worker->onConnect = function($connection) use (&$users)
{
$connection->onWebSocketConnect = function($connection) use (&$users)
{
$users[$connection->id] = $connection;
};
};

$ws_worker->onClose = function($connection) use(&$users)
{
unset($users[$connection->id]);
};

// Run worker
Worker::runAll();
```

example of a client that sends data but does not receive it

```
$localsocket = 'tcp://127.0.0.1:1234';
$user = 'tester01';
$message = 'test';

$instance = stream_socket_client($localsocket);

$stdin = fopen('php://stdin', 'r');
while (true) {
$message = trim(fgets($stdin));

fwrite($instance, json_encode(['user' => $user, 'message' => $message]) . "\n");

}
```

an example on js

```
ws = new WebSocket("ws://127.0.0.1:8000/?user=tester01");

const bodyElement = document.getElementById('wrapper');

bodyElement.addEventListener('keyup', event => {

console.log(123123)
let positionData = {
user: 'user',
message: 'message',
};

ws.send(JSON.stringify(positionData));
});

ws.addEventListener('message', (event) => {
console.log(event.data)
});
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.