Java捕获超时错误,获取java.io.IOException:读取失败,套接字可能关闭或超时,通过蓝牙打印机打印时读取ret:-1...
发布日期:2022-03-15 11:49:58 浏览次数:18 分类:技术文章

本文共 1436 字,大约阅读时间需要 4 分钟。

Code is working fine for first time only, if i am trying to connect it again it is throwing this exception:

read failed, socket might closed or timeout, read ret: -1

This is my function for connecting to the bluetooth printer:

public boolean openBT(Context context) throws IOException {

try {

// Standard SerialPortService ID

UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);

mBluetoothAdapter.cancelDiscovery();

mmSocket.connect();

mmOutputStream = new DataOutputStream(mmSocket.getOutputStream());

mmInputStream = new DataInputStream(mmSocket.getInputStream());

} catch (NullPointerException e) {

e.printStackTrace();

return false;

} catch (Exception e) {

e.printStackTrace();

return false;

}

return true;

}

解决方案

You should close your socket after using it :

public boolean openBT(Context context) throws IOException {

try {

// Standard SerialPortService ID

UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);

mBluetoothAdapter.cancelDiscovery();

mmSocket.connect();

mmOutputStream = new DataOutputStream(mmSocket.getOutputStream());

mmInputStream = new DataInputStream(mmSocket.getInputStream());

mmSocket.close(); //Socket closed

} catch (NullPointerException e) {

e.printStackTrace();

return false;

} catch (Exception e) {

e.printStackTrace();

return false;

}

return true;}

转载地址:https://blog.csdn.net/weixin_34596012/article/details/118842823 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:中飞院计算机学院毕业后侍遇,【毕业季·计算机学院】年华在指间流动,出门已是江湖...
下一篇:java的优缺点 以及它用于什么,Java中的接口 - 它们用于什么?

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年04月15日 10时07分28秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章