forked from cubiclesoft/ultimate-web-scraper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_websocket_client.php
60 lines (52 loc) · 1.53 KB
/
test_websocket_client.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
// Requires both the WebBrowser and HTTP classes to work.
require_once "support/websocket.php";
require_once "support/web_browser.php";
require_once "support/http.php";
$ws = new WebSocket();
// The first parameter is the WebSocket server.
// The second parameter is the Origin URL.
$result = $ws->Connect("ws://localhost:5578/math/?apikey=123456789101112", "http://localhost");
if (!$result["success"])
{
var_dump($result);
exit();
}
// Send a text frame (just an example).
// Get the answer to 5 + 10.
$data = array(
"pre" => "5",
"op" => "+",
"post" => "10",
);
$result = $ws->Write(json_encode($data), WebSocket::FRAMETYPE_TEXT);
// Send a binary frame in two fragments (just an example).
// Get the answer to 5 * 10.
$data["op"] = "*";
$data2 = json_encode($data);
$y = (int)(strlen($data2) / 2);
$result = $ws->Write(substr($data2, 0, $y), WebSocket::FRAMETYPE_BINARY, false);
$result = $ws->Write(substr($data2, $y), WebSocket::FRAMETYPE_BINARY);
// Main loop.
$result = $ws->Wait();
while ($result["success"])
{
do
{
$result = $ws->Read();
if (!$result["success"]) break;
if ($result["data"] !== false)
{
// Do something with the data.
echo "Raw message from server:\n";
var_dump($result["data"]);
echo "\n";
$data = json_decode($result["data"]["payload"], true);
echo "The server said: " . $data["question"] . " = " . $data["answer"] . "\n\n";
}
} while ($result["data"] !== false);
$result = $ws->Wait();
}
// An error occurred.
var_dump($result);
?>