【问题标题】:BufferedWriter doesn't write all the data on a BluetoothSocketBufferedWriter 不会将所有数据写入 BluetoothSocket
【发布时间】:2017-03-23 18:01:15
【问题描述】:

我编写了一个在 BluetoothSocket 中写入的方法,但它并没有写入所有内容。

public static String BluetoothPrint(String cFichero, String cMAC){

String cFail = "Fail";

try{
    BluetoothAdapter oBluetoothAdapter  = BluetoothAdapter.getDefaultAdapter();
    BluetoothDevice  oDispositivo       = oBluetoothAdapter.getRemoteDevice(cMAC);

    cFail = "Fail socket";      

    Method          oMethod = oDispositivo.getClass().getMethod("createRfcommSocket",new Class[] { int.class });
    BluetoothSocket     oSocket = (BluetoothSocket) oMethod.invoke(oDispositivo, Integer.valueOf(1));
    oSocket.connect();

    cFail = "Fail getOutput";

    BufferedWriter oStream = new BufferedWriter(new OutputStreamWriter(oSocket.getOutputStream(), "ISO-8859-1"));

    cFail = "Fail write";

    oStream.flush();
    oStream.write(cFichero,0,cFichero.length());
    oStream.close();

    oSocket.close()

}catch(Exception e){return cFail;}
return "ok";}

这个方法有大小限制吗?我尝试写入的文件大小为 5,37KB

【问题讨论】:

  • 你怎么知道不是所有的东西都是写的?此外,您应该在 finally 块中关闭事物,这样就不会在出现异常时泄漏流或套接字。
  • @Gray 因为我在 Socket 中得到了信息。
  • 抛出了什么异常?

标签: java android sockets bluetooth bufferedwriter


【解决方案1】:

我终于找到了答案。问题是套接字'oSocket'的缓冲区。 我重写了我的方法以分块发送数据并等待。

public static String BluetoothPrint(String cFichero, String cMAC)
{
String cFail = "Fail";
byte oByte;
byte[] msg = cFichero.getBytes();

try{
    BluetoothAdapter oBluetoothAdapter  = BluetoothAdapter.getDefaultAdapter();
    BluetoothDevice  oDispositivo       = oBluetoothAdapter.getRemoteDevice(cMAC);

    cFail = "Fail socket";      

    Method oMethod = oDispositivo.getClass().getMethod("createRfcommSocket",new Class[] { int.class });
    BluetoothSocket oSocket = (BluetoothSocket) oMethod.invoke(oDispositivo, Integer.valueOf(1));
    oSocket.connect();

    cFail = "Fail getOutput";

    BufferedOutputStream(oSocket.getOutputStream());
    BufferedOutputStream btoutputstream = new BufferedOutputStream(oSocket.getOutputStream(),512);

    cFail = "Fail write";

    int off = 0;

    while(off < msg.length){

        btoutputstream.write(msg,off,64);
        btoutputstream.flush();

        Thread.sleep(600);

        off += 64; 
    }

    btoutputstream.close();
    oSocket.close();

}catch(Exception e){return cFail;}

return "ok";
}

【讨论】:

  • 问题是socket的缓冲区怎么样?这些更改没有理由解决任何问题。还有什么变化?
  • 套接字属于打印机。那台打印机的缓冲区只有 1,5Kb。使用这种方法,我的设备等待足够长的时间让打印机清空他的缓冲区。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 2019-04-16
  • 1970-01-01
  • 2012-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多