workerman icon indicating copy to clipboard operation
workerman copied to clipboard

Tcp server documentation, wrong?

Open StefanoV1989 opened this issue 8 months ago • 2 comments

I was using Workerman to make a TCP server using the example in the readme, and it doesn't work.

The onMessage callback is not called and the connection gets close after any message (tried with telnet too).

After trying everything, I decided to put the onMessage callback inside the onConnect callback, and it worked!

So I think the documentation in the readme, just for the TCP example, is wrong.

It was just my case?

StefanoV1989 avatar Apr 11 '25 06:04 StefanoV1989

HI Stefano,

Workerman supports multiple protocols — like HTTP, WebSocket, TCP, and UDP — and their event handling differs. In the case of pure TCP, it’s a stream-based protocol, which means it doesn’t have a native concept of a “message” unless you define one yourself (like delimiting by \n, length-prefixed frames, etc.).

That’s why, in raw TCP mode, onMessage doesn’t behave as expected — because TCP just delivers a stream of bytes. The onMessage callback is more meaningful when using application-layer protocols like WebSocket or the built-in Text protocol.

Recommended solutions for TCP: 1.Use the onReceive event instead of onMessage: $tcp_worker->onReceive = function($connection, $data) { $connection->send("hello " . $data); }; 2.Alternatively, define a protocol layer (like Text or Json) that wraps around TCP, so onMessage behaves as intended. 3.If sticking with raw TCP and you really want to use onMessage, you can assign it per connection inside onConnect, as I tried above — but this might not be the cleanest solution.

So no — it wasn't just “my case.” It’s more of a misunderstanding around protocol behavior. The documentation example could benefit from a small note explaining that onMessage is not automatically triggered in raw TCP mode unless a higher-level protocol is used.

zikezhang avatar Apr 11 '25 15:04 zikezhang