Question

In going through some socket connection code of mine, I noticed this method:

public void write(String line) throws IOException, NullPointerException {
    log.fine(line);
    byte[] bytes = line.getBytes();
    outputStream.write(bytes);   // append 13 and 10 here before the write
    outputStream.write(13);
    outputStream.write(10);
    outputStream.flush();

}

and it occurs that I may be introducing some latency, perhaps, by writing the line and then appending CR and LF before flushing.

Would it be more efficient to append the CR and LF to the byte array, making for only a single call to outputStream.write() instead of three calls?

The context is a socket connection based MUD client. (No, SSH isn't an option, MUD games use telnet.)

Because it's not an ArrayList or something easy to work with, I'm not sure how big the array is, so I don't know the index to the last element. Iterate the Array into a new array, and then append CR and LF to the next elements? That seems weird. I'm not sure how to avoid a NullPointerException when adding to the end of the array.

Was it helpful?

Solution

If your outputStream object is at one level a BufferedOutputStream, then you are good. Nothing to worry about. However, even if you don't have a BufferedOutputStream, socket streams are always buffered, I think.

To answer your question, you could do something like this:

byte[] msg = line.getBytes(Charset.forName("UTF-8"));
byte[] output = new byte[msg.length + 2];
System.arraycopy(msg, 0, output, 0, msg.length);
output[msg.length] = (byte) 13;
output[msg.length] = (byte) 10;
outputStream.write(output);

Or even better would be:

byte[] msg = line.concat("\r\n").getBytes(Charset.forName("UTF-8"));
outputStream.write(msg);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top