我正在尝试管理我的电话和另一个蓝牙设备之间的连接。我使用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());没有错误,所以我猜插座还是打开的.这是怎么回事?
非常感谢你的帮助!
发布于 2011-10-17 19:08:02
这个问题有几个原因。典型的原因是您写入的连接已被对等方关闭。换句话说,应用程序协议错误。
此外,您的异常处理也需要工作。如果你在一个套接字上得到任何IOException,而不是超时,你必须关闭它,它是死的。
发布于 2011-10-18 17:46:20
好的,我试着添加了一些wait()函数,看起来还不错……因为这是读和写的超时之间的问题。我认为this post应该工作。
发布于 2011-10-17 19:02:14
删除行dOut.flush();这会导致连接重置。
https://stackoverflow.com/questions/7792457
复制相似问题