一次从.txt获取 16 个字节



我有两个文件,一个正在发送,一个正在接收。 我有两者之间的联系。

可以发送带有以下内容的文本:

// Prepare a message 
 messageToSend = "text that is sent";
 lengthMessageToSend = messageToSend.length(); 
 sendingBuffer = messageToSend.getBytes();

// Send the message
 myLink.sendFrame(sendingBuffer, lengthMessageToSend);
 System.out.println(lengthMessageToSend);

并接收:

// Display the message
  messageReceived = new String(receivingBuffer, 0, lengthMessageReceived);
  System.out.println("Message received is: [" + messageReceived + "]"); 
// Prepare a message  
  messageToSend = "1";
  lengthMessageToSend = messageToSend.length(); 
  sendingBuffer = messageToSend.getBytes();
 // Send the message
  myLink.sendFrame(sendingBuffer, lengthMessageToSend);

我现在尝试发送的文本来自.txt,但只是在有效负载中一次发送 16 个字节:

[ 序列 |林 |有效载荷 |校验和 ] --> 表示总标头为 19 个字节。

最好的

方法是什么?

一次只读取 16 个字节(8 个字符)??如果是这样,如何?

每次循环

并递增 16 i,此i表示messageToSend.getBytes()偏移量的开始 - 然后将接下来的 16 个字节(从 ii+16,处理剩余少于 16 个字节的情况)放入"数据包"并将其发送出去。

此外,对getBytes()或环境设置使用显式编码可能会导致"意外的行为更改"。

这样的基本实现可能如下所示:

byte[] data = messageToSend.getBytes("UTF-8"); // Specify encoding!
// "For all data, stepping by 16 bytes at a time.."
for (int i = 0; i < data.length; i += 16) {
   // How many bytes actually remain (or 16 if more than 16 remain)
   var frameSize = Math.min(16, data.length - i);
   // Construct frame data from data in i..i+frameSize and send.
   // If you want to ALWAYS send 16 bytes, update as appropriate.
   byte[] frameData = new byte[frameSize];
   System.arraycopy(data, i, frameData, 0, frameSize);
   sendFrame(frameData, frameSize);
}

必须调整代码以添加序列号,但这应该不难,因为它总是递增 1。

读取发生类似:使用数据包标头并根据长度/成帧数据处理剩余的缓冲区(可能包括下一个数据包的开始)。

// Assuming new frames are always copied-to-start and that there
// if a complete frame ready (can be determined from frame size with)
// two reads. If not, keep reading..
byte[] receivingBuffer = ..;
int offset = 0;
int seq = receivingBuffer[offset++];
int frameSize = receivingBuffer[offset++];
// Again, use an encoding
String content = new String(receivingBuffer, offset, frameSize, "UTF-8");
offset += frameSize;
int checksum = receivingBuffer[offset++];
// Use offset to move extra data in receivingBuffer to start
// of buffer to make it easy to reset offset to 0 and repeat above.

最新更新