java - Most effective way to read from a TCP socket -


i have tcp connection server, implemented socket , streams. during session, server can send number of messages - must read , process them all.

i created thread, checks , reads data in infinite cycle:

in = socket.getinputstream(); bytearrayoutputstream baos = null; byte[] buf = new byte[4096]; while(!isinterrupted()) {    baos = new bytearrayoutputstream();    for(int s; ( s = in.read(buf)) != -1; ) {        baos.write(buf, 0, s);        if(in.available() <= 0 ) {            readchunk(baos.tobytearray());        }    } } 

but actually, it's not efficient - puts cpu under heavy load, , somehow bytes stick previous answer.

what effective , elegant way resolve situation?

tcp not message-oriented, it's stream-oriented. means if send 2 messages aa , bb, it's quite possible read on different occasions values aabb, a b b, abb, aab b, aa bb (where spaces indicate different read attempts).

you need handle either message size or message delimiters on own, no longer needing in.available(). also, code copies same data @ least 3 times different buffers, , consider using bufferedinputstream on socket.getinputstream().


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -