reading data from a java socket

Hello all,

I’m trying to write a serversocket that reads a postscript stream from a printer driver and writes that stream into a file.

I’m reading data in a while loop and trying to close the connection on input.readLine() = null but my problem is that if I use this statement I’ll lose some data.
Also I tried while(true) but my connection is not closing anymore(After all the stream is transmitted it keeps sending null to my file.)

How can I detect if socket activity is finished?

Thanks,
Ionut

Did you actually write input.readLine() = null in your program or is it correctly written as input.readLine() == null?

Also why are you using line oriented input? Postscript isn’t guaranteed to have line breaks regularly or even end with a line feed. Lots of PostScript files contain binary data. You should treat the data as a stream of bytes and not assume lines.

In my program I used while(input.readLine() != null){ read … data from socket};

And yes when I use input.readLine () seems that I loose some binary data.

So … what kind of methods I should use to read binary data and check if socket activity was finished?

Read data a block at a time. You should be able to find the javadoc for the class.

I’ll try that!

Thank you very much! I tried this way and it’s working.

while(input.readLine() != null) {
    read data from the socket
}

Here, every alternate line is lost! You are reading a line to test if it is null or not. When you read again inside the loop, the line read in the conditional statement is already lost.

In the end I used something like:

byte] buf = new byte[4096];
for (int br = clientSocket.getInputStream().read(buf);
br > -1;
br = clientSocket.getInputStream().read(buf)) {

        outFile.write(buf, 0, br);

}

This way I was able to read all the data.

Thanks to all for the replies.

If you take advantage of testing the result of an assignment which IIRC works just as well in Java as in C, you can simplify that to:

int br = 0;
while ((br = clientSocket.getInputStream().read(buf)) > -1) {
   outFile.write(buf, 0, br);
}

[QUOTE=ken_yap;2104686]Did you actually write input.readLine() = null in your program or is it correctly written as input.readLine() == null?

Also why are you using line oriented input? Postscript isn’t guaranteed to have line breaks regularly or even end with a line feed. Lots of PostScript files contain binary data. You should treat the data as a stream of bytes and not assume lines.[/QUOTE]

san diego audio video | san diego home theater installation | san diego plasma installation | san diego lcd installation | san diego hdtv installation