java tcp read,在Java中读取tcp流的最有效方法

I'm having to modify some client side code because the comms protocol wasn't defined properly.

I'd assummed that a tcp message from the server would terminate in a new line so I used reader.readLine() to read my Data.

Now I've been told that this is not the case and that instead the first 4 chars of the message are the message length and then I have to read the rest of the message.

What is the most efficient sensible way to do this?

my general Idea was as follows:

Create a 4 char array

Read in first 4 characters

Determine what the message length is

Create a new array of message length

read into the new array.

Here is an example of the code (reader is a BufferedReader created elsewhere):

char[] chars = new char[4];

int charCount = reader.read(chars);

String messageLengthString = new String(chars);

int messageLength = Integer.parseInt(messageLengthString);

chars = new char[messageLength];

charCount = reader.read(chars);

if (charCount != messageLength)

{

// Something went wrong...

}

I know how to do this, but Do I have to worry about the character buffers not being filled? if so how should I deal with this happening?

解决方案

Chars in Java are for text data. Are you sure the protocol really defines the length of the message this way? More likely it's the first four bytes to represent a 32-bit length.

If you're talking to C or C++ developers they may be using "char" as a synonym for "byte".

EDIT: Okay, based on the comment:

I would create a method which took a Reader and a count and repeatedly called read() until it had read the right amount of data, or threw an exception. Something like this:

public static String readFully(Reader reader, int length) throws IOException

{

char[] buffer = new char[length];

int totalRead = 0;

while (totalRead < length)

{

int read = reader.read(buffer, totalRead, length-totalRead);

if (read == -1)

{

throw new IOException("Insufficient data");

}

totalRead += read;

}

return new String(buffer);

}

Then your code can be:

String lengthText = readFully(reader, 4);

int length = Integer.parseInt(lengthText);

String data = readFully(reader, length);

// Use data now

You should check what happens when they want to send fewer than 1000 (or more than 9999) characters though...

你可能感兴趣的:(java,tcp,read)