因此,对于一项家庭作业,我有一个有关如何封送数据和进行封送的示例。

他们给我们的结构是这样的:
事件是一个接口。
Wireformat是“继承”事件的类。
WireFormatWidget是具有实际代码的类,具有编组和取消编组。

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

我有一个问题是,当我创建Wireformat对象时。我遇到了试图封送数据的线程问题。

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


接口结构将数据定义为消息,将消息类型定义为整数,时间戳(我假设是Date和该日期的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中打印出标识符时,我得到的是空值,而不是我硬编码的预期标识符。因此,我一定不能适当地“继承”。我究竟做错了什么?

编辑: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作为标识符。

09-06 12:13