![](/img/trans.png)
[英]Cassandra-unit : java.io.IOException: Connection reset by peer
[英]java.io.IOException: Connection reset by peer
我正在嘗試管理手機和另一個藍牙設備之間的連接。 我正在使用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());
沒有錯誤,所以我猜插座仍然打開......這里發生了什么?
非常感謝你的幫助!
這個問題有幾個原因。 典型的原因是您已寫入已由對等方關閉的連接。 換句話說,應用程序協議錯誤。
您的異常處理也需要工作。 如果在超時之外的套接字上得到任何IOException,你必須關閉它,它已經死了。
好吧,我嘗試添加一些wait()函數,它似乎有效......因為它是讀寫超時之間的問題。 我認為這篇文章應該有效......
刪除行dOut.flush();
這導致連接重置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.