-1

I'm making a group-chatting program by using socket but cant write my Message object into the socket objectOutputStream. The server side objectInputStream found nothing (avalible = 0). I have try to flush but it dosen't work. Please help guy.

enum MessageStatus implements Serializable {Mess, Offline};
public class Message implements Serializable{
String mess;
String senderName;
int senderID;
MessageStatus type;

public Message(String mess, int SenderID, String SenderName) {
    this.mess = mess;
    this.senderID = SenderID;
    this.senderName = SenderName;
}

I have tried to write it like this:

Message msg = new Message(txtChat.getText().trim(), user.id,    user.name);
msg.type = MessageStatus.Mess;
try {
        user.Output.writeObject(msg);
        user.Output.flush();

My socket is ok, i have tried to write some string or int and it work but not my object. I have tried to take it as message or object in sever side socket object inputstream but it throw out .ClassNotFoundException I think my object was not been writen into socket

Duc Lu
  • 1
  • 2

1 Answers1

1

Don't rely on available() to know if there is something to load indeed it only returns the number of bytes that can be read without blocking.

Using your code if I do this:

    Message msg = new Message("Hello", 123, "world");
    System.out.printf("Before serialization = %s%n", msg);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(byteArrayOutputStream);
    oos.writeObject(msg);
    oos.flush();
    oos.close();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(byteArrayInputStream);
    System.out.printf("available = %d%n", ois.available());
    Message message = (Message) ois.readObject();
    System.out.printf("After deserialization = %s%n", message);
    ois.close();

The output is:

Before serialization = Message{mess='Hello', senderName='world', senderID=123, type=Mess}
available = 0
After deserialization = Message{mess='Hello', senderName='world', senderID=123, type=Mess}

I can see that the message is properly serialized and deserialized but still available returns 0 which proves with an example that you must not trust available for such need.

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122