Pass Uint8List from dart to java over a TCPSocket

问题: I need to pass an Uint8List to a byte[] array in java over a TCPSocket. There is size mismatch at both ends. PS: I am a beginner in dart. I have tried socket.add(buf), so...

问题:

I need to pass an Uint8List to a byte[] array in java over a TCPSocket. There is size mismatch at both ends. PS: I am a beginner in dart.

I have tried socket.add(buf), socket.write(buf), socket.writeAll(buf) but none of them worked

Code in Flutter side (TCP client)

 void readVoiceData(Uint8List buf) {    
     print("Send data size:"+buf.lengthInBytes.toString());    
     socket.add(buf);   
 }

OUTPUT: Send data size: 1280

Code Snippet on java side (TCP server)

in = new DataInputStream(clientSocket.getInputStream());  
    Log.d(TAG, "****Opened InputStream*******");
     while (!isInterrupted()) {                   
     if (mTrack != null) {
     try {
     in.read(bytes);        
     Log.d(TAG, "Received data size"+bytes.length);                                    
                                }
}

OUTPUT: Received data size: 1

I am sure the socket connection has been established correctly as I am able to send Strings and Integers flawlessly over them.


回答1:

This happens because the read() method of the FilterInputStream (DataInput is his son) reads just the next avaliable byte. Thou, if you want to get the total size of the InputStream, do something like:

  size = in.available(); //returns an estimate of number of bytes avaliable on the stream
  buf = new byte[size]; 
  realLength= in.read(buf, 0, size);

This code snippet is taken from here.

  • 发表于 2019-01-11 22:50
  • 阅读 ( 597 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除