0

私の出力は "[B@b42cbf" で、エラーはありません。

「Server Check」という文字列である必要があります。

アドレスではなく文字列を出力するようにコードを修正するにはどうすればよいですか?

オブジェクトを出力するコードは何度か変更されましたが、現在は次のようになっています。

System.out.println(packet.getMessage().toString());

私のパケットクラスは次のとおりです。

import java.io.Serializable;

public class Packet implements Serializable {

    final public short MESSAGE = 0;
    final public short COMMAND = 1;

    private String _ip;
    private short _type;
    private String _source;
    private String _destination;
    private byte[] _message;


    public Packet(String ip, short type, String source, String destination,
            byte[] message) {
        this._ip = ip;
        this._type = type;
        this._source = source;
        this._destination = destination;
        this._message = message;
    }

    public String getIP() {
        return this._ip;
    }

    public Short getType() {
        return this._type;
    }

    public String getSource() {
        return this._source;
    }

    public String getDestination() {
        return this._destination;
    }

    public byte[] getMessage() {
        return this._message;
    }
}

ObjectOutputStream を介してパケットを送信し、ObjectInputStream で受信します。オブジェクトは (Packet) でパケットに変換されます。これがどのように機能するかは、次のように確認できます。

public void sendPacket(Packet packet) throws NoConnection {
        if (this._isConnected) {
            try {
                this._oos.writeObject(packet);
                this._oos.flush();  // Makes packet send
            } catch (Exception e) {
                e.printStackTrace();
                this._isConnected = false;
                throw new NoConnection("No notification of disconnection...");
            }
        } else {
            throw new NoConnection("No connection...");
        }
    }

これがリスナーです。

@Override
    public void run() {
        try {
            this._ois = new ObjectInputStream(this._socket.getInputStream());
            Packet packet = (Packet) this._ois.readObject();
            this._listener.addPacket(packet);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
4

3 に答える 3

9

[B@b42cbfバイト配列、つまりバイナリデータを印刷すると得られるものです。

そこから文字列を取得するには、エンコーディングを知る必要があります。その後、次のことができます。

String messageStr = new String(packet.getMessage(), "UTF-8");

もちろん、それはそのデータが実際に印刷可能なデータである場合にのみ機能します。

于 2011-12-21T08:28:30.703 に答える
2

getMessage()バイト配列を返します。配列のtoString()メソッドは、その内容を出力しません。getMessage()代わりにreturn aを作成できますString

于 2011-12-21T08:30:48.420 に答える
1

これは正常です。配列オブジェクトを文字列として出力しています。

用途: System.out.println(new String(packet.getMessage());.

つまり、その中のバイトから文字列を構築します。これはデフォルトのエンコーディングを使用することに注意してください。

于 2011-12-21T08:29:36.370 に答える