如何在字节缓冲区中表示目标列表

发布于 2024-12-17 16:28:24 字数 254 浏览 3 评论 0原文

一个简单的问题:

我有一个目标列表,例如 A、B、C、D、E...,我需要将此目标列表放入字节缓冲区并使用 java 套接字发送到客户端。在客户端,它将解析字节缓冲区并获取目标列表。

我找到两种方法来做到这一点:首先,使用 dest_list_size + dest_list 的格式。那么上面的例子就变成:5+A;B;C;D;E;其次,使用哈希集来保存目的地列表。那么如何将哈希集转换为字节数组并转换为哈希集呢?

我想验证一下哪条路更好?谢谢。

A simple question:

I have a destination list, for example, A, B, C, D, E, ... and I need to put this destiantion list to a bytebuffer and send to a client using a java socket. At the client side, it will parse the bytebuffer and get the destination list.

I find two ways to do this: firstly, using format of dest_list_size + dest_list. Then the above example will becomes: 5+A;B;C;D;E; secondly, using a hashset to hold the destination list. Then how to transform hashset to a byte arrays and translates to a hashset?

I want to verify which way is better to go? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

榕城若虚 2024-12-24 16:28:24

最好的方法是将其序列化为更标准的内容,例如 json。您可以使用现有的库,即 jackson

The best way would be to serialize it to something more standard like json. You can use existing libraries i.e. jackson.

和我恋爱吧 2024-12-24 16:28:24

取决于您的目标字段的类型。

ByteBuffer bb = ...
Set<Character> destinations = new LinkedHashSet<Character>(
        Arrays.asList('A',  'B',  'C',  'D',  'E'));
bb.put((byte) destinations.size());
for (char b : destinations) bb.put((byte) b);

bb.flip();

int size = bb.get();
Set<Character> destinations2 = new LinkedHashSet<Character>();
for (int i = 0; i < size; i++)
    destinations2.add((char) bb.get());
System.out.println(destinations2);

打印

[A, B, C, D, E]

如果您有不同类型的目标或可能超过 127 个目标,您需要根据需要更改写入该字段/值的方式。

Depending on the type of you destination field.

ByteBuffer bb = ...
Set<Character> destinations = new LinkedHashSet<Character>(
        Arrays.asList('A',  'B',  'C',  'D',  'E'));
bb.put((byte) destinations.size());
for (char b : destinations) bb.put((byte) b);

bb.flip();

int size = bb.get();
Set<Character> destinations2 = new LinkedHashSet<Character>();
for (int i = 0; i < size; i++)
    destinations2.add((char) bb.get());
System.out.println(destinations2);

prints

[A, B, C, D, E]

If you have a different type of destination or more than 127 destinations possible you need to change how you write that field/value as required.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文