Java 字节和字符串转换[校验和]
我有一个文件,我需要通过UDP可靠地传输(我知道TCP是更好的选择)。因此,我需要一个校验和来验证数据的一致性 在发件人处,我已使用以下代码格式化数据包:Java 字节和字符串转换[校验和],java,string,udp,bytearray,checksum,Java,String,Udp,Bytearray,Checksum,我有一个文件,我需要通过UDP可靠地传输(我知道TCP是更好的选择)。因此,我需要一个校验和来验证数据的一致性 在发件人处,我已使用以下代码格式化数据包: static class Generator { public static byte[] format(String type, int sequence_no, byte[] data) { String header = type + "|" + sequence_no + "|" + Validator.g
static class Generator {
public static byte[] format(String type, int sequence_no, byte[] data) {
String header = type + "|" + sequence_no + "|" + Validator.getChecksum(data) + "|";
String temp = new String(data, 0, data.length);
String combine = header + temp;
return combine.getBytes();
}
}
这将返回要发送的数据的最后一个字节
static class Validator {
public static String getChecksum(byte[] bytes) {
CRC32 crc = new CRC32();
crc.update(bytes, 0, bytes.length);
return crc.getValue() + "";
}
}
BufferedFileReader将数据读入字节数组,该数组将被发送到此Generate.format方法以附加适当的头信息
然而,在我的接收器端,我似乎无法返回相同数量的字节,尽管数据“看起来是一样的”
String raw = new String(packet.getData(), 0, packet.getLength());
String[] split = raw.split("\\|");
System.out.println(split[3].getBytes().length);
我怀疑缓冲区中的字节与接收到的字符串不完全相等,从而导致接收器获得不同的输出
有人能发现错误吗?作为
字符串的数据是否包含您试图拆分的字符“|”
?您能发布您的输出以及您期望的输出吗?@Bubletan是的,我使用了“|”作为分隔符。该代码适用于普通字符串数据,但是,当数据以字节形式存在时,则不适用work@Verim输出文字难以辨认�=“$&)+.136格式如下..我试图确保传输时传输的数据(例如,长度950)在接收时也将是(长度950)。但是,字节长度似乎发生了变化。您知道发送数据可以拆分和合并这些数据。这意味着对于一次发送(),您可以在另一端“获得多个接收(),对于多次发送())您“可以”获得一个receive()。因此您必须自己拆分收到的包。