On a Bluetooth connection, why is it impossible to to let a thread read from a DataInputStream if that stream was opened by another thread? Below is a slightly altered version of the HelloWorld bluetooth example (works with BTsend on the PC side). The original example works well with my setup. The code is so that it simply starts a separate thread for reading out the received data.
The listed application simply blocks on dis.readInt(), never receiving any integers (yes the BTsend program is connected to the NXT and is sending the integers). Changing this application so that the for loop replaces this.start() and Thread.Sleep(60000) makes the application work again...
Best regards,
Peter
- Code: Select all
import lejos.nxt.*;
import lejos.nxt.comm.BTConnection;
import lejos.nxt.comm.Bluetooth;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.DataOutputStream;
import java.io.OutputStream;
public class HelloWorld extends Thread {
private DataInputStream dis;
private DataOutputStream dos;
public static void main(String[] aArg) {
HelloWorld hello = new HelloWorld();
hello.doIt();
}
public void doIt() {
String connected = "Connected";
String waiting = "Waiting";
while (true) {
try {
LCD.drawString(waiting, 0, 0);
LCD.refresh();
BTConnection btc = Bluetooth.waitForConnection();
LCD.clear();
LCD.drawString(connected, 0, 0);
LCD.refresh();
InputStream is = btc.openInputStream();
OutputStream os = btc.openOutputStream();
DataInputStream dis = new DataInputStream(is);
DataOutputStream dos = new DataOutputStream(os);
this.start();
Thread.sleep(60000); // which should be long enough for the other thread to send out the integers
dis.close();
dos.close();
btc.close();
LCD.clear();
} catch (Exception e) {
}
}
}
public void run() {
for (int i = 0; i < 100; i++) {
try {
int ii = dis.readInt();
LCD.drawInt(ii, 3, 0, 1);
LCD.refresh();
dos.writeInt(-ii);
dos.flush();
} catch (Exception e) {
}
}
}
}

