我有3个设备通过蓝牙PAN网络连接。
可能的通信方法是蓝牙和JAVA中的套接字连接。我已经可以从DEVICE 2控制DEVICE 1了 - 但命令没有中继到DEVICE 3.这是我用于服务器的代码:
主要
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;
}
}
}
}
我现在正在使用TCP-Client作为我的设备3 - 但是当我通过DEVICE 2发送命令时它没有显示任何文本。我怎么能意识到我的项目 - 我做错了什么?
答案 0 :(得分:0)
这适用于您的服务器。创建所有连接的列表
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);
}
以及向其他客户发送消息的方法
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);
}
}
}
和,RelayThread的构造函数保持Main
Main main;
public RelayThread (Socket clientSocket,Main main) {
this.socket = clientSocket;
this.main = main;
}
和,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
}