java - 如何为 TCP 流编码数据?

标签 java class interface

因此,对于家庭作业,我有一个如何编码和解码数据的示例。

他们给我们的结构是这样的: 事件是一个接口(interface)。 Wireformat 是一个“继承”Event 的类。 WireFormatWidget 是一个具有 marshal 和 unmarshal 实际代码的类。

我有单独的线程来处理使用 TCP 以字节数组形式发送数据。

我遇到的问题是当我创建 Wireformat 对象时。我遇到了尝试编码(marshal)数据的线程问题。

Exception in thread "main" java.lang.NullPointerException
    at myhw.WriteFormatWidget.getBytes(WriteFormatWidget.java:38)

接口(interface)结构将数据定义为消息、整数消息类型、时间戳(我假设是日期和该日期的 getTime)和跟踪器。我不确定跟踪器是什么。

我被告知这种结构是发送数据的最佳方法,这就是我尝试实现这种代码风格的原因。

WriteFormatWidget 包含以下内容:

private int type;
private long timestamp;
private String identifier;
private int tracker;

因此,对于我的线格式,我将其创建为一个扩展 WireFormatWidget 并实现 Event 的类,因为这是 Eclipse 不会吐出错误或建议更改 WireFormatWidget 或 Event 的唯一方法。

现在,当我对特定的线格式进行硬编码时,我将其实例化,但它似乎无法使用我用于相同变量的硬编码值来调用 getBytes()。

public class MyWireFormat extends WireFormatWidget implements Event {
    private String identifier = "here is my custom wireformat";
    ....

当我打印 WireFormatWidget 中 getBytes 中的标识符时,我得到 null 而不是我硬编码的预期标识符。所以我一定不能适本地“继承”。我做错了什么?

编辑:WireFormatWidget(给定)

public class WriteFormatWidget {
private int type;
private long timestamp;
private String identifier;
private int tracker;

    public byte[] getBytes() throws IOException {
        byte[] marshalledBytes = null;
        ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(new BufferedOutputStream(baOutputStream));

        dout.writeInt(type);
        dout.writeLong(timestamp);

        System.out.println("getBytes using identifier: " + identifier);

        byte[] identifierBytes = identifier.getBytes();
        int elementLength = identifierBytes.length;
        dout.writeInt(elementLength);
        dout.write(identifierBytes);

        dout.writeInt(tracker);

        dout.flush();
        marshalledBytes = baOutputStream.toByteArray();

        baOutputStream.close();
        dout.close();

        return marshalledBytes;
    }
}

我将通过不发布解码部分来节省空间。但反过来也是一样的。

我遇到的问题是从客户端打印数据作为我事先发送的内容的证明。

所以我将执行一个简单的测试,例如打印类型或打印标识符。它失败了,我有空。

最佳答案

您没有初始化 WireFormatWidget#identifier。它已声明但从未初始化。向 WireFormatWidget 添加一个构造函数并提供一个 String 作为标识符。

关于java - 如何为 TCP 流编码数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60133383/

相关文章:

java - 为什么数据成员用默认值初始化,而局部变量则不然?

delphi - 在 Delphi 中将接口(interface)引入现有的类层次结构

reflection - 使用嵌入在结构中的接口(interface)进行反射 - 如何检测 "real"函数?

java - 如何更改已运行实例的 Java 类的代码?

java - 在 Java 中显示 Rserve 的结果(R 和 Java 的集成)

c# - 关于类的属性更改时如何使 UI 使用react的任何想法?

python - AttributeError: 'NoneType' 对象没有属性

Delphi插件框架

java - 创建自定义微调器时如何实现 getView

java - 线程 "main"org.openqa.selenium.NoSuchElementException : An element could not be located on the page using the given search parameters 中出现异常