【问题标题】:Socket prematurely closed in Bluetooth Chat example蓝牙聊天示例中的套接字过早关闭
【发布时间】:2015-03-12 11:58:51
【问题描述】:

我一直在理解"Bluetooth Chat" example 的源代码。 BluetoothChatService 包含一个线程(称为ConnectThread),在创建套接字(本地称为mmSocket)后,如果一切顺利,调用连接方法:

connected(mmSocket, mDevice);

所以,mmSocket 作为参数传递。连接的方法具有以下签名:

public synchronized void connected(BluetoothSocket socket, BluetoothDevice device);

并包括这一行:

mConnectThread.cancel(); //mConnetcThread is an instance of ConnectThread

cancel 方法包含以下代码:

mmSocket.close();

所以 mmSocket 关闭了,作为连接方法的第一个参数传递的套接字也应该关闭(因为它引用的是同一个对象),并且当下一个代码调用时:

mConnectedThread = newConnectedThread(socket); // socket should be already closed

我认为这是错误的,因为套接字现在已关闭,我无法对其执行任何操作(例如在与套接字关联的 InputStreamOutputStream 上读取或写入数据)。我错了吗?

【问题讨论】:

    标签: java android sockets bluetooth android-bluetooth


    【解决方案1】:

    您可以看到,在 connected 方法中取消 mConnectThread 之前,它会检查是否不为空。同时这里是从第 434 行开始对connected 的完整调用:

     // Reset the ConnectThread because we're done
     synchronized (BluetoothChatService.this) {
         mConnectThread = null;
     }
     // Start the connected thread
     connected(mmSocket, mmDevice);
    

    可见mConnectThread在调用connected之前被设置为null

    【讨论】:

    • 你是对的,我写错了我的代码mConnectedThread = null;而不是mConnectThread = null;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多