Jeff wrote:
> I'd appreciate advice on the best approach to reading objects from sockets.
> Is it possible to make a blocking read or do I have to poll?
>
> My server application sends data to my client application via TCP socket in
> time intervals ranging from every few milliseconds to 100s of milliseconds.
> I'd like to use a blocking read in the client to avoid unnecessary sleeps,
> reads, etc. But readObject does not block in my tests, it returns null if
> there is no data. Right now, my client sleeps for 10ms, then attempts to
> read.
>
> Can someone tell me how to do a blocking read when retrieving objects? Is
> there a better approach?
>
> Thanks
>
> here's my input stream creation:
> is = new ObjectInputStream(new BufferedInputStream(sock.getInputStream()));
>
I think you may be having some other problems. Even though the docs
don't say that the ObjectInputStream.readObject() blocks, it does say it
returns an object. It doesn't say that it returns a null but it can if
it is sent a null. I have never seen the behaviour that you describe so
I think your problem lies somewhere else.
I did write a couple of little test programs and tried them on my
computer but not across the network. I wouldn't think it would make any
difference but try them and see how they work for you.
Just start the two programs in a DOS window or Terminal and type some
characters on the keyboard on the tc (test client) end and they should
show up on the ts (test server) end. An empty line terminates both
programs.
import java.io.*;
import java.net.*;
public class ts {
public static void main (String[] args) {
try {
ServerSocket ss = new ServerSocket(33333);
Socket s = ss.accept();
ss.close();
ObjectInputStream ois = new
ObjectInputStream(s.getInputStream());
String str = "";
do {
str = (String)ois.readObject();
System.out.println(str);
} while (!str.equals("")) ;
} catch (Exception e) {
System.out.println(e);
}
}
}
import java.io.*;
import java.net.*;
public class tc {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost",33333);
ObjectOutputStream oos =
new ObjectOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
String str = "";
do {
str = br.readLine();
oos.writeObject(str);
oos.flush();
} while (!str.equals("")) ;
oos.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
--
Knute Johnson
email s/nospam/knute/
Molon labe...
|