Kunal
Kunal

Reputation: 111

How to write a multi-protocol handler on a single port using Netty?

I'm a newbie on Netty, and I'm wondering how to read/handle incoming TCP data when the TCP client sometimes sends variable length binary records (hex) and sometimes sends variable length ASCII records, none of which are delimited by carriage return or line feed.

The TCP client is sending a stream of bytes as follows:

  1. A binary stream of bytes that begins with '$' but has a varying number of bytes and not terminated by any character, and

  2. An ASCII stream of bytes that begins with '(' and ends with ')' but has a varying number of bytes and not terminated by any character

Both sets of records arrive on the same port.

How would I need to code my Netty-based TCP server to handle/read both?

Thanks in advance.

Kunal

Upvotes: 3

Views: 2319

Answers (2)

Norman Maurer
Norman Maurer

Reputation: 23567

Checkout the port unification example. It does exactly what you want.

Upvotes: 5

Renaud
Renaud

Reputation: 2129

First, don't mix everything together '$' is a Char, it can be represented by one single Byte in most encoding but this is hardly the case for a common char (in UTF-8, char a variable length encoded and can use 1, 2 or 3 Bytes).

It depends the length of your stream.

1) The easiest solution, if it can fit inside the memory of your sender, is to use a frame with a two fields header:

  • one Byte for the type (byte or String)
  • 2 Bytes (using an unsigned Int16 for instance) for the length of the frame the (number of Bytes of data).

Than, you could use a FrameDecoder to receive and decode the whole frame.

2) If your stream is huge and cannot fit inside the memory, you have two solutions:

  • Split your stream into frames (with a little overhead because of the header of each frame)
  • Use the Channel.close() event to notify the EndOfStream (which is easier but can cause some latency issues if you need to create a new connection and do some handshaking again and again...

In every case Netty prodives some StringEncoder and StringDecoder for streaming Strings. And also some FrameDecoder and FrameEncoder with all kinds of usefull headers.

Upvotes: 0

Related Questions