Dear all,
I am working on a mobile communicator and after establishing connection to the server using following method (to illustrate that I am using StreamConnection, InputStream and OutputStream) I distribute inputStream and outputStream between two separate threads, lets call them Sender and Receiver.
Connection method:
private InputStream inputStream;
private OutputStream outputStream;
private StreamConnection connection;
public void connect(String host, String port) throws IOException {
String connectionString = "socket://" + host + ":" + port;
connection = (StreamConnection) Connector.open(connectionString);
inputStream = connection.openDataInputStream();
outputStream = connection.openOutputStream();
}
Sender thread is waiting for anything to appear in the out buffer. When output buffer is empty, Sender waits (by calling wait()
method on sender thread). Any input into the output buffer calls notify()
method on the sending thread.
Receiver thread polls the InputStream using int available()
method and when there is something to receive, it calls blocking int read()
method. Everything works like a charm in various emulators and few devicdes I have handy around.
However there is one phone that seems to missbehave. Whenever one thread calls available()
or read()
on InputThread object, while the other thread calls write()
on the OutputStream object, the Input stream finishes. All subsequent reads will return value -1, which means that the InputStream got closed.
After massive google-fu, I came accross this post on nokia forums, where simplex/duplex properties of a device are being discussed and that seems to be the case with the device I have troubles with. Normally (99% of the time) calls to read() and write() can be simultaneous without any problems.
My question is then: Did anybody came accross similar problems? How did/would you sort out the issue of one thread independently reading, while another is independently writing into the established connection, so that they do not call read() or available() while calling write()?
Any pointers in any directions greatly appreciated!