java - 一次从 .txt 获取 16 个字节

标签 java string network-programming byte

我有两个文件,一个发送,一个接收。我知道两者之间有联系。

可以通过以下方式发送文本:

// 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 个字节:

[ 序列 |伦 |有效负载| CHECKSUM ] --> 总共 19 个字节的 header 。

最好的方法是什么?

一次只读取 16 个字节(8 个字符)?如果是这样怎么办?

最佳答案

循环并每次将 i 增加 16,此 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);
}

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

读取过程类似:根据长度/帧数据消耗数据包 header 并处理剩余缓冲区(可能包括下一个数据包的开始)。

// 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.

关于java - 一次从 .txt 获取 16 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29705872/

相关文章:

java - 在重复的字符串中查找任何字符出现的总次数

java - GIF 基于每台计算机的速度?

network-programming - 使用DPDK创建tcp/ip连接

c - 使用 poll() 运行一个简单的 TCP 服务器,如何触发事件 "artificially"?

java - 测试类中没有可以由可用注入(inject)满足的构造函数

python - 有没有办法将字符串变量传递到 python .loc/.iloc 中?

java - 池和堆的关系

python - 为什么Python在这里打印大括号?

c# - 连接的TCP套接字如何同时发送/接收多个文件?

java - Maven - 使用 JDK 7 为 JVM 5 编译