java.io.IOException:由peer重置连接

时间:2011-10-17 10:30:15

标签: java android

我正在尝试管理手机和其他蓝牙设备之间的连接。我正在使用java Android做这一切。这是我用于使用我的设备连接套接字的代码:

首先,我找到了蓝牙设备并创建了套接字:

BluetoothDevice btNonin = null;
for (BluetoothDevice device : pairedDevices)
{
        if (device.getName().contains("Nonin")) 
        {           
            // We found the device      
            exito = true;
            try
            {
                // We create the socket
                Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
                socket = (BluetoothSocket) m.invoke(device, 1);
                socket.connect();
            }
            catch (Exception e)
            {
                Dialogs.showInfoDialog(NONIN_OFF, this);
            }
       }
}

我是否创建了数据字节,我希望远程蓝牙接收使用一些代码将ASCII转换为字节:

String[] parts = mensaje.split(" ");
String res = "";
if(parts != null && parts.length > 0)
{
    for (String s : parts)
    {
        if (s.length() != 2)
           break;
            byte izq, der;
        izq = (byte)char2ascii(s.charAt(0));
        der = (byte)char2ascii(s.charAt(1));
        byte aux2 = (byte)((izq << 4) + der);
        res += (char)aux2;
    }
}

然后我将数据发送到蓝牙设备:

// We send the data bytes
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeBytes(res);
dOut.flush();

直到这里工作正常。它将数据字节发送到我的设备。但后来我想等待我的设备的任何响应,然后我试试这个:

//Waiting for response
DataInputStream dIn = new DataInputStream(socket.getInputStream());
try
{
    byte response = '\u0000';
    while (dIn.readByte() == '\u0000')
    {
        response = dIn.readByte();
    }
    Dialogs.showInfoDialog("Response: " + response, this);
}
catch (Exception e)
{
    Dialogs.showInfoDialog("No se ha recibido respuesta: " + e.toString(), this);
}

但是,在我创建dIn.readByte的行上,它显示消息Error:

java.io.IOException: Connection reset by peer

我不知道为什么连接被重置或发生了什么,因为我可以调试该行:

DataInputStream dIn = new DataInputStream(socket.getInputStream());

没有错误,所以我猜套接字仍然打开......这里发生了什么?

非常感谢你的帮助!

3 个答案:

答案 0 :(得分:7)

导致此问题的原因有多种。典型的原因是您已写入已由对等方关闭的连接。换句话说,应用程序协议错误。

此外,您的异常处理需要工作。如果你在套接字上获得任何IOException而不是超时,你必须关闭它,它已经死了。

答案 1 :(得分:-1)

好的,我尝试添加一些wait()函数,它似乎有效......因为这是读写超时之间的问题。我认为this post应该有用......

答案 2 :(得分:-2)

删除导致连接重置的行dOut.flush();

相关问题