簡體   English   中英

序列化對象通過UDP發送到Java中的客戶端后具有空值

[英]Serialized object has null values after being sent via UDP to client in java

這個問題使我無所適從。 這是針對我目前正在開發的非常簡單的在線多人游戲。

我目前能夠通過udp向我的客戶端發送數據包,並且它們似乎沒問題。 但是,當我將序列化的對象發送給客戶端並在另一端反序列化時,嘗試訪問所需的值時會出現NullPointerExceptions。 我已經驗證了對象已在服務器端正確序列化(反序列化並檢查了數據),因此我有99%的把握要對發送數據包的代碼做錯什么。

以下是用於從服務器序列化和發送“ Datagram”對象的代碼:

    DatagramPacket sendPacket = null;

    byte[] buf = null;

    //Serialize the datagram object to send as a UDP packet
    try {

        // Serialize to a byte array
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(bos);   
        out.writeObject(data);
        buf = bos.toByteArray(); 

        out.close();
        bos.close();

    } catch (IOException e) {
    }

    try {
        sendPacket = new DatagramPacket( buf, buf.length,
                InetAddress.getLocalHost(), 4004);
    } catch (UnknownHostException e){}

    try {
        DatagramSocket sendSocket = new DatagramSocket();
        sendSocket.send( sendPacket );
        changed = true;
    }catch (IOException e) {}

序列化的“數據”對象充滿了正確的值; 我相信這一點。

另一個相關的代碼塊是客戶端上的接收塊:

public Datagram readDatagram() {

    byte[] buff = new byte[20000];
    DatagramPacket packet = new DatagramPacket(buff, buff.length);
    DatagramSocket receiver = null;

    try {
        receiver = new DatagramSocket(4004);
        receiver.receive(packet);
    } catch (IOException e) {
        System.out.println("ERROR2");
    }

    Datagram data = null;// = new Datagram();

    try {
        // Deserialize from a byte array
        ByteArrayInputStream bis = new ByteArrayInputStream(buff);
        ObjectInput in = new ObjectInputStream(bis);
        data = (Datagram) in.readObject();

        bis.close();
        in.close();
    } catch (ClassNotFoundException e) {
    } catch (IOException e) {
        System.out.println("ERROR3");
    }

    for (int i = 0; i < 35; i++) {
        System.out.print(data.getLevel()[i]);
    }

    receiver.close();

    return data;

}

當我嘗試在反序列化之后讀取任何值時,會收到NullPointerException。 如果有人能指出正確的方向,我將非常高興。

哦,我現在有意發送到localHost只是為了進行測試。 我的客戶端和服務器都在我的計算機上運行。

在發送和接收端,您都在捕獲和壓縮異常。 這很有可能會隱藏可以幫助您診斷問題的證據。 即使不是這種情況,擠壓這樣的異常情況也是危險的做法。

我敢打賭,正在接收結束代碼中引發ClassNotFoundException 這將使您的data == null ,然后將導致以下循環中的NPE。

您的代碼可能存在的一個問題是您在關閉ObjectOutputStream之前調用toByteArray()

out.writeObject(data);
buf = bos.toByteArray();

out.close();
bos.close(); 

如果序列化數據的某些部分直到close()才寫入輸出流,在這種情況下它們將丟失。 關閉流后,嘗試調用toByteArray()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM