문제

I have created a server-client chat room style application and I'm trying to transfer a custom object which I have created containing the message and the username of the person using client/server application. To do this I have created a separate class called message which contains two static variables, one called username and one called messageText:

public class message implements Serializable{

    static String username = "";
    static String messageText = "";

    public message(String message, String user){
        System.out.println("Setting username and messageText");
        username = user;
        messageText = message;
    }

    public message(Object recievedObject){
        username = ((message) recievedObject).getUsername();
        messageText = ((message) recievedObject).getMessageText();
    }
}

I send an object of this class from my server to a client as follows:

message sendMessage = new message(enteredText, "SERVER");
output.writeObject(sendMessage);

It is accepted by the client as follows:

message recievedMessage = (message) input.readObject();
cw.say(recievedMessage.getMessageText(), recievedMessage.getUsername());

However both methods above getMessageText() and getUsername() will return whatever the variable was initialized with on the receiving end, and return the correct values on the sending side.

A few hours of trying to fix this problem has provided no solution, so any help that you guys can give me is very, very appreciated! Thanks.

도움이 되었습니까?

해결책

static fields are not serialized. If you make them non-static it should work

다른 팁

Static variables are shared by all instances of a class. That means it doesn't make much sense to serialize them.

In a message, the fields "username" and "messageText" are likely not meant to be static, unless there is only one message in existence.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top