I have a problem with my client - server apps which I developed in JAVA. I use Socket and ServerSocket from java.net* package. When client connect to the server, client sends message for example 7200 bytes. In server I use InputStream. Sometimes I receive whole message (7200 bytes), but many times I receive less than 7200 bytes. Is there any way in JAVA to receive whole message and close connection? Maybe should I use other library to tcp/ip connection in JAVA?
-
Instead of describing your code consider posting actual (but simplified to minimum) code which will let us reproduce your problem, or at least see how you organized your solution.Pshemo– Pshemo2015-03-18 18:41:43 +00:00Commented Mar 18, 2015 at 18:41
2 Answers
Probably this will help: InputStream.read() documentation.
Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer.
This method will not block until the entire byte buffer filled up or stream end reached. Instead, it returns as much data as available at the moment.
This is not likely to happen when reading from files, but quite normal for sockets.
The actual number of bytes, which were written into byte-buffer is returned, so you can you that to decide if there's enough data.
You can use read(buf, start, len), to start not from beginning of buffer but continue data block. For example, if you are reading exactly 7200 bytes, do:
byte [] buf = new byte[7200];
int len = 7200;
int pos=0;
while(len > 0) {
int rd = is.read(buf, pos, len);
if(rd<0) {
//premature EOF
break;
}
pos += rd;
len -= rd;
}
Otherwise if you do not know message length up front you have several options. Among them:
- Send message length as first 4 bytes, then always read 4 bytes first, then allocate buffer of necesary size and read into it
- Read into buffer until you receive "END-OF-MESSAGE" marker. Like, for example "END-OF-LINE". When you find it - stop reading and process message.
4 Comments
I suggest jgroups (http://www.jgroups.org/manual/html/index.html) from jboss to tcpip communications