/** * Send a message to WebSocket clients (use port + 1 for SSL connections) */ public static function send($type, $msg, $to = false) { $proto = self::$ssl ? 'wss' : 'ws'; $port = self::$ssl ? self::$port + 1 : self::$port; $ws = new WebSocketClient("{$proto}://localhost:" . self::$port); $ws->send(json_encode(array('type' => $type, 'from' => self::$clientID, 'msg' => $msg, 'to' => $to))); $ws->close(); }
echo "examples: php client.php -c 100 -n 10000" . PHP_EOL; return; } $clients = $opt['c']; $count = $opt['n']; $size = empty($opt['k']) ? 0 : $opt['k']; require __DIR__ . "/WebSocketClient.php"; $host = '127.0.0.1'; $prot = 9501; $client = new WebSocketClient($host, $prot); $data = $client->connect(); //echo $data; $data = "data"; if (!empty($size)) { $data = str_repeat("A", $size * 1024); } for ($i = 0; $i < $count; $i++) { $client->send("hello swoole, number:" . $i . " data:" . $data); $recvData = ""; //while(1) { $tmp = $client->recv(); if (empty($tmp)) { break; } $recvData .= $tmp; //} echo $recvData . "size:" . strlen($recvData) . PHP_EOL; } echo PHP_EOL . "======" . PHP_EOL; sleep(1); echo 'finish' . PHP_EOL;
function websocket(Swoole_Benchmark $bc) { static $client = null; static $i; $start = microtime(true); if (empty($client)) { $client = new WebSocketClient($bc->server_config['host'], $bc->server_config['port']); if (!$client->connect()) { echo "connect failed\n"; return false; } $end = microtime(true); $conn_use = $end - $start; $bc->max_conn_time = $conn_use; $i = 0; $start = $end; } /*--------写入Sokcet-------*/ if (!$client->send($bc->send_data)) { echo "send failed\n"; return false; } $end = microtime(true); $write_use = $end - $start; if ($write_use > $bc->max_write_time) { $bc->max_write_time = $write_use; } $start = $end; /*--------读取Sokcet-------*/ $ret = $client->recv(); //var_dump($ret); $i++; if (empty($ret)) { echo $bc->pid, "#{$i}@", " is lost\n"; return false; } $end = microtime(true); $read_use = $end - $start; if ($read_use > $bc->max_read_time) { $bc->max_read_time = $read_use; } return true; }
<?php require __DIR__ . '/WebSocketClient.class.php'; // Connect to the WebSocket server $ws = new WebSocketClient('ws://localhost:1729'); // Send some messages $ws->send('Foo'); $ws->send('Bar'); $ws->send('Baz'); // Close the connection $ws->close(); // Now do the same for SSL $ws = new WebSocketClient('wss://localhost:1730'); $ws->send('Foo'); $ws->send('Bar'); $ws->send('Baz'); $ws->close();
<?php namespace WSSC; require_once './src/ConnectionException.php'; require_once './src/IWscCommons.php'; require_once './src/WscMain.php'; require_once './src/WebSocketClient.php'; $client = new WebSocketClient('ws://localhost:8000/notifications/messanger/vkjsndfvjn23243'); $client->send('{"user_id" : 123}'); echo $client->receive();