Role of Communication Protocols

Since TCP is stream-based, the request data sent by the client flows to the server like a stream of water. When the server detects incoming data, it should check whether the data is complete, as it is possible that only part of a request's data has arrived at the server, or even that multiple requests have arrived at the server concatenated together. To determine whether a request has fully arrived or to separate requests that are concatenated together, a communication protocol must be established.

Why Establish a Protocol in Workerman?

Traditional PHP development is primarily web-based, mostly utilizing HTTP protocol. The parsing and processing of the HTTP protocol are handled solely by the WebServer, so developers do not concern themselves with protocol matters. However, when we need to develop based on non-HTTP protocols, developers need to consider the protocol.

Protocols Supported by Workerman

Workerman currently supports HTTP, websocket, text protocol (see appendix for description), frame protocol (see appendix for description), and ws protocol (see appendix for description). When communication based on these protocols is required, they can be used directly. The method is to specify the protocol when initializing the Worker, for example:

use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';

// websocket://0.0.0.0:2345 indicates listening on port 2345 with websocket protocol
$websocket_worker = new Worker('websocket://0.0.0.0:2345');

// text protocol
$text_worker = new Worker('text://0.0.0.0:2346');

// frame protocol
$frame_worker = new Worker('frame://0.0.0.0:2347');

// tcp Worker, directly based on socket transmission, not using any application layer protocol
$tcp_worker = new Worker('tcp://0.0.0.0:2348');

// udp Worker, not using any application layer protocol
$udp_worker = new Worker('udp://0.0.0.0:2349');

// unix domain Worker, not using any application layer protocol
$unix_worker = new Worker('unix:///tmp/wm.sock');

Using a Custom Communication Protocol

When the built-in communication protocols of Workerman do not meet the development requirements, developers can customize their own communication protocols. The customization method is detailed in the next section.

Note:

Workerman has a built-in text protocol, where the protocol format is text + newline character. The text protocol is very simple to develop and debug, suitable for the vast majority of custom protocol scenarios, and supports telnet debugging. If developers want to create their own application protocol, they can use the text protocol directly without additional development.

For more information regarding the text protocol, refer to the "Appendix Text Protocol Section".