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

I am new to Netty, and I am wondering how to read / process TCP input when a TCP client sometimes sends variable length binary (hex) records and sometimes sends variable length ASCII records, none of which are limited by carriage return or line feed.

The TCP client sends a stream of bytes as follows:

  • A binary stream of bytes that starts with '$' but has a variable number of bytes and is not interrupted by any character, but

  • ASCII stream of bytes starting with '(' and ending with ')' but has a variable number of bytes and does not end with a character

Both sets of records are sent to the same port.

How do I need to encode my Netty TCP server to process / read both?

Thanks in advance.

Kunal

+3
source share
2 answers

Checkout an example of port aggregation . He does exactly what you want.

+5
source

First, do not mix everything together. '$' is a Char, it can be represented by a single byte in most encodings, but this is hardly the case for a common char (in UTF-8, char is encoded variable length and can use 1, 2 or 3 bytes).

It depends on the length of your stream.

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

  • one byte for type (byte or string)
  • 2 ( Int16, ) ( ).

, FrameDecoder .

2) , :

  • ( - )
  • Channel.close(), EndOfStream ( , , ...

Netty StringEncoder StringDecoder . FrameDecoder FrameEncoder .

0

All Articles