我有3个通过蓝牙PAN网络连接的设备。
可能的通信方法是JAVA中的蓝牙和套接字连接。我已经可以从DEVICE 2控制DEVICE 1-但命令不会中继到DEVICE3。这是我用于服务器的代码:
主要的
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螺纹
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作为我的DEVICE 3,但是当我通过DEVICE 2发送命令时,它不显示任何文本。我如何实现我的项目-我在做什么错?
这是为您的服务器。创建所有连接的列表
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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句