serversocket - Netty ChannelRead method -
i novice in using netty framework. meet problem, utilize netty write serversocket. goal of server receiving message hardware.the hardware sends byte everytime. server , hardware have protocol -- every message starts '#',and ended '*'.
@sharable class serverhandler extends channelinboundhandleradapter { @override public void channelread(channelhandlercontext ctx, object msg) { bytbuf in = (bytebuf) msg; charbuffer charbuffer = charbuffer.allocate(100); string recedata ; byte tmp; seek { while (in.isreadable()) { tmp = in.readbyte(); if (tmp != 42) { charbuffer.append((char) tmp); // system.out.println(string.valueof(charbuffer.array())); } else { //means receive byte '*' charbuffer.append('*'); count = 0; recdata = string.valueof(charbuffer.array()); logger.debug("receive message " + recdata); } }catch(exception e){ e.printstacktrace(); } } }
however, problem occurs. when hardware first send #abcd
, server store #abcd
hardware may send efg*
.because of netty asynchronous , event driven, method channelread()
run begin end.so print efg*
,not #abcdefg*
i think lot. finally, have thought. utilize attribuekey
threadlocal
binds array store received byte channel.then #.....*
array. array very big. not method. have improve method solve problem? give thanks help
take in netty user guide - dealing stream-based transport. message can become fragmented - in case may receive "#abcd" followed "efg*". since allocating charbuffer each time, original charbuffer contains "#abcd". on sec method call, charbuffer contains "efg*".
a solution utilize bytetomessagedecoder. decode() repeatedly called (by netty framework) until in bytebuf empty (i.e., decode code empties it). can in decode() maintain returning until "in" bytebuf contain * char. 1 time does, write contents of bytebuf "out" list origin # *. remaining bytes after * left on in bytebuf , process continue.
netty serversocket channel
No comments:
Post a Comment