You must create a new stream for each message; otherwise, every call to toByteArray()
will send all previous messages again.
A better approach is probably to wrap the OutputStream
of a TCP socket with a GZIPOutputStream
:
printStream = new PrintStream(new GZIPOutputStream(sock.getOutputStream()));
Also don't forget to flush the PrintStream
after every message or nothing will happen.
If speed is really that important, you should consider to use a DatagramChannel
instead of the old (slow) steam API. This should get you started:
ByteBuffer buffer = ByteBuffer.allocate( 1000 );
ByteBufferOutputStream bufferOutput = new ByteBufferOutputStream( buffer );
GZIPOutputStream output = new GZIPOutputStream( bufferOutput );
OutputStreamWriter writer = new OutputStreamWriter( output, "UTF-8" );
writer.write( "log message\n" );
writer.close();
sock.getChannel().open(); // do this once
sock.getChannel().write( buffer ); // Send compressed data
Note: You can reuse the buffer
by rewinding it but all the streams must be created once per message.