I have 3 devices which are connected via a bluetooth PAN network.
The possible communication method is bluetooth and a socket connection in JAVA. I can already control DEVICE 1 from DEVICE 2 - but the commands are not relayed to DEVICE 3. This is the code which I am using for my server:
Main
try {
serverSocket = new ServerSocket( 1111 );
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new thread for a client
new RelayThread(socket).start();
}
RelayThread THREAD
public class RelayThread extends Thread {
protected Socket socket;
BufferedReader bufferedReader;
public RelayThread (Socket clientSocket) {
this.socket = clientSocket;
}
public void run() {
Singleton motors = Singleton.getInstance();
InputStream inp = null;
BufferedReader brinp = null;
DataOutputStream out = null;
try {
inp = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(inp, "UTF-8");
bufferedReader = new BufferedReader(isr);
out = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
return;
}
while (true) {
try {
String command= bufferedReader.readLine();
if ((command== null) || command.equalsIgnoreCase("QUIT")) {
socket.close();
return;
}
else {
// do ROBOT actions
/*
* SERVER ACTIONS
*/
// notify the other client of the delivered LINE
out.writeBytes(command);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
I'm using TCP-Client as my DEVICE 3 right now - but it doesn't show any text when I send commands via DEVICE 2. How could I realize my project - and what am I doing wrong?
this is for your server. Creating a list of all connections
List<RelayThread> clients = new ArrayList<RelayThread>();
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new thread for a client
RelayThread relay = new RelayThread(socket,this);
relay.start();
clients.add(relay);
}
and a method to send message to other clients
public void sendCommand(String command, RelayThread source){
for (int i=0;i<clients.size();i++){
if (clients.get(i) != source) {
clients.get(i).sendCommand(command);
}
}
}
and, constructor of RelayThread to keep Main
Main main;
public RelayThread (Socket clientSocket,Main main) {
this.socket = clientSocket;
this.main = main;
}
and, a sender message in RelayThread
public void sendCommand(String command){
out.writeBytes((command+"\r\n").getBytes()); // I suggest you add a parser charachter, like \r\n. then client can understand message ends
}