【问题标题】:java.io.IOException: Connection reset by peerjava.io.IOException:对等方重置连接
【发布时间】:2011-10-18 17:46:19
【问题描述】:

我正在尝试管理我的手机和其他蓝牙设备之间的连接。我正在使用 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 的那一行,它显示了错误消息:

java.io.IOException: Connection reset by peer

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

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

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

非常感谢您的帮助!

【问题讨论】:

  • @mozarty 权限与它到底有什么关系?

标签: java android


【解决方案1】:

这个问题有几个原因。典型的原因是您已写入已被对等方关闭的连接。换句话说,应用程序协议错误。

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

【讨论】:

  • 我不知道出了什么问题,因为我打开了套接字以进行写入,但是当我尝试从中读取时,它崩溃了。也许我需要另一个插座来阅读?
  • @Sonhja 将其打开以供写入并不意味着对等方将读取您编写的所有内容。你必须确保你发送的东西是正确的。异常可能发生在导致它的写入之后。
  • 该消息是正确的。它仍然没有解决我的问题。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 这个答案完全不正确。冲洗不会导致此异常。 Writing 会导致此异常。刷新可以让它在不同的时间出现,但实际上这个特定的 flush() 什么都不做,DataOutputStream.flush() 是一个空操作。
    猜你喜欢
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多