客户端/服务器/客户端通过套接字通信

Client / Server / Client Communication via sockets

我有 3 台设备通过蓝牙 PAN 网络连接。

JAVA 中可能的通信方式是蓝牙和套接字连接。我已经可以从设备 2 控制设备 1 - 但命令不会中继到设备 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 线程

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
}