You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多台Android设备蓝牙连接求助:多客户端连服务器失败

解决Android服务器多客户端连接失败的问题

Hey there! Let's break down why you're hitting that java.io.IOException: read failed, socket might closed or timeout, read ret: -1 error when trying to connect multiple clients to your Android server, and fix it step by step.

核心问题分析

That error usually pops up when your server isn't set up to handle concurrent client connections properly. Most single-client socket implementations block the main listening thread once a client connects, so subsequent clients can't get through—either they time out, or the connection drops immediately after being established.

具体修复步骤

1. 为每个客户端连接启动独立线程

Your server needs to keep listening for new clients while handling existing ones. Wrap each incoming socket connection in a separate thread so the main ServerSocket.accept() call isn't blocked. Here's a simplified example:

// 服务器端核心监听逻辑
private static final int PORT = 8080;
private ServerSocket serverSocket;
// 用线程安全的集合管理所有客户端处理器
private List<ClientHandler> clientHandlers = new CopyOnWriteArrayList<>();

public void startServer() {
    new Thread(() -> {
        try {
            serverSocket = new ServerSocket(PORT);
            Log.d("Server", "Listening on port " + PORT);
            
            while (!serverSocket.isClosed()) {
                // 阻塞等待新客户端连接
                Socket clientSocket = serverSocket.accept();
                Log.d("Server", "New client connected: " + clientSocket.getInetAddress());
                
                // 创建并启动客户端处理线程
                ClientHandler handler = new ClientHandler(clientSocket);
                clientHandlers.add(handler);
                new Thread(handler).start();
            }
        } catch (IOException e) {
            Log.e("Server", "Server error", e);
        }
    }).start();
}

// 客户端通信处理类
private class ClientHandler implements Runnable {
    private Socket clientSocket;
    private BufferedReader input;
    private PrintWriter output;

    public ClientHandler(Socket socket) {
        this.clientSocket = socket;
    }

    @Override
    public void run() {
        try {
            // 初始化输入输出流
            input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            output = new PrintWriter(clientSocket.getOutputStream(), true);
            
            String message;
            // 持续读取客户端消息
            while ((message = input.readLine()) != null) {
                Log.d("Server", "Received: " + message);
                // 可选:把消息广播给所有其他客户端
                broadcastMessage(message, this);
            }
        } catch (IOException e) {
            Log.e("ClientHandler", "Client connection error", e);
        } finally {
            // 关闭资源并从客户端列表移除
            try {
                input.close();
                output.close();
                clientSocket.close();
                clientHandlers.remove(this);
                Log.d("Server", "Client disconnected");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 发送消息给当前客户端
    public void sendMessage(String message) {
        output.println(message);
    }
}

// 广播消息给所有客户端(排除发送者)
private void broadcastMessage(String message, ClientHandler sender) {
    for (ClientHandler handler : clientHandlers) {
        if (handler != sender) {
            handler.sendMessage(message);
        }
    }
}

2. 修复客户端连接的超时与配置

On the client side, make sure you're setting a reasonable connection timeout and using the correct server IP (don't use 127.0.0.1—use the server's actual local LAN IP):

// 客户端连接代码示例
public void connectToServer(String serverIp) {
    new Thread(() -> {
        try {
            Socket socket = new Socket();
            // 设置5秒连接超时,避免无限等待
            socket.connect(new InetSocketAddress(serverIp, PORT), 5000);
            Log.d("Client", "Connected to server");
            
            // 后续的读写逻辑...
        } catch (IOException e) {
            Log.e("Client", "Connection failed", e);
        }
    }).start();
}

3. 检查必要的权限与网络配置

Double-check your AndroidManifest.xml to ensure you have the right permissions:

<!-- 网络权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 允许明文网络流量(如果不用SSL) -->
<application
    ...
    android:usesCleartextTraffic="true">
    ...
</application>

Also, confirm all devices are on the same Wi-Fi network, and the server device isn't blocking incoming connections via a firewall or network settings.

4. 排查意外的Socket关闭

Make sure your server doesn't accidentally close the ServerSocket when handling a client error. The main listening loop should only exit when you intentionally stop the server.

调试小技巧

  • Check Logcat for the full stack trace of the error—this will tell you if the failure happens during connection establishment or while reading/writing data.
  • Test with a small number of clients first (2-3) to confirm the setup works before scaling up.

内容的提问来源于stack exchange,提问作者Kapil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:24:05