【问题标题】:Android TCP server broadcastAndroid TCP 服务器广播
【发布时间】:2012-10-14 04:18:52
【问题描述】:

我正在开发一个使用 TCP 进行设备连接的 Android 应用程序。问题是我是套接字编程的新手。我已经成功制作了服务器和客户端代码。每个客户端都可以连接到服务器,服务器可以回复客户端。但我似乎无法让服务器同时向所有连接的客户端发送消息。使服务器向客户端广播消息的步骤是什么? 这是服务器代码:

ServerSocket server = null;
try {
    server = new ServerSocket(9092); // start listening on the port
} catch (IOException e) {
    Log.d("btnCreate onClick", "Could not listen on port: 9092");
}
Socket client = null;
while(true) {
    try {
        client = server.accept();
    } catch (IOException e) {
        Log.d("btnCreate onClick", "Accept Failed");
    }
    //start a new thread to handle this client
    Thread t = new Thread(new ClientConn(client));
    t.start();
}

还有服务器线程:

class ClientConn implements Runnable {
    private Socket client;

    ClientConn(Socket client) {
        this.client = client;
    }

    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            /* obtain an input stream to this client ... */
            in = new BufferedReader(new InputStreamReader(
                        client.getInputStream()));
            /* ... and an output stream to the same client */
            out = new PrintWriter(client.getOutputStream(), true);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        String msg;
        try {
            while ((msg = in.readLine()) != null) {
                Log.d("ClientConn", "Client says: " + msg);
                out.println(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

【问题讨论】:

  • 您能解释一下在您的上下文中“广播”是什么意思吗? TCP 没有广播。
  • 编辑了我的问题。我希望服务器向所有连接的客户端发送消息。不是叫广播吗?我是套接字编程的新手。

标签: android tcp broadcast


【解决方案1】:

TCP 是一种点对点连接协议。这意味着当您在套接字上发送消息时,它只会发送给 一个 接收者。其他 IP 协议(​​如 UDP)确实具有“广播”模式,其中一个数据包可以发送到多个接收者,但 TCP 则没有。

要让您的服务器向所有客户端发送相同的消息,服务器必须在每个客户端的每个套接字上发送一条消息。

【讨论】:

  • 所以我应该把我所有客户端的IP都存储起来,然后将消息一一发送给他们?我应该把代码放在哪里?在 ClientConn 上?
  • 根据您发布的代码(ClientConn),您已经为每个客户端打开了一个套接字句柄。因此,您只需要某种方式告诉该类在其client 套接字上发送消息。
  • 好的,我会尽力告诉你的。感谢您的启发。 :D
猜你喜欢
  • 2012-07-18
  • 1970-01-01
  • 2013-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-01
相关资源
最近更新 更多