text Protocol
Workerman defines a text protocol called text, which is formatted as
data packet + newline, meaning that a newline at the end of each data packet indicates the end of the packet.
For example, the following strings buffer1 and buffer2 conform to the text protocol:
// Text followed by a newline
$buffer1 = 'abcdefghijklmn
';
// In PHP, "\n" within double quotes represents a newline character, e.g. "\n"
$buffer2 = '{"type":"say", "content":"hello"}'."\n";
// Establish a socket connection with the server
$client = stream_socket_client('tcp://127.0.0.1:5678');
// Send buffer1 data using the text protocol
fwrite($client, $buffer1);
// Send buffer2 data using the text protocol
fwrite($client, $buffer2);
The text protocol is very simple and easy to use. If developers need their own protocol, such as transmitting data with a mobile app or communicating with hardware, they can consider using the text protocol, as it is very convenient for development and debugging.
Debugging the text Protocol
The text protocol can be debugged using a telnet client, for example, in the following example:
Create a file named test.php
require_once __DIR__ . '/Workerman/Autoloader.php';
use Workerman\Worker;
$text_worker = new Worker("text://0.0.0.0:5678");
$text_worker->onMessage = function($connection, $data)
{
var_dump($data);
$connection->send("hello world");
};
Worker::runAll();
Execute php test.php start and the output will be as follows:
php test.php start
Workerman[test.php] start in DEBUG mode
----------------------- WORKERMAN -----------------------------
Workerman version:3.2.7 PHP version:5.4.37
------------------------ WORKERS -------------------------------
user worker listen processes status
root none myTextProtocol://0.0.0.0:5678 1 [OK]
----------------------------------------------------------------
Press Ctrl-C to quit. Start success.
Open another terminal and test using telnet (it is recommended to use the telnet of a Linux system)
Assuming it is a local test,
In the terminal, execute telnet 127.0.0.1 5678
Then type hi and press Enter
You will receive the data hello world\n
telnet 127.0.0.1 5678
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
hi
hello world