Java ObjectInputStream只接收最后一个对象

时间:2017-03-15 16:29:38

标签: java sockets serversocket objectinputstream objectoutputstream

如果我同时向我的ObjectOutputStream写两个对象,它会导致ObjectInputStream仅接收第二个对象而不处理第一个对象。这就像第二条消息是覆盖第一条消息。

try
    {
        serverObjectWriter.writeObject(new Message("", this.getUsername() + " ist dem Chat beigetreten."));
        serverObjectWriter.flush();

        serverObjectWriter.writeObject(new Message(MessageType.CLIENT_JOINED, this.getUsername()));
        serverObjectWriter.flush();
    }
    catch(IOException io)
    {
        ...
    }

所以在这种情况下我只收到第二条消息。我不知道第一个对象发生了什么。 我还尝试将它们放在分离的线程中,并通过join()方法以同步方式发送它们。

这是我收到物品的部分:

private class ServerHandler implements Runnable
{
    //
    Message message;

    @Override public void run()
    {
        try
        {   
            while((message = (Message) serverObjectReader.readObject()) != null)
            {
                switch(message.getMessageType())
                {
                case MESSAGE:
                    HPos pos;

                    if(message.getSender().equals(getUsername()))
                        pos = HPos.RIGHT;
                    else if(message.getSender().equals(""))
                        pos = HPos.CENTER;
                    else 
                        pos = HPos.LEFT;

                    Platform.runLater(() -> cgui.appendMessage(message.getSender(), message.getMessage(), message.getTime(), pos));
                    break;
                case CLIENT_JOINED:
                    Platform.runLater(() -> cgui.addClientToClientList(message.getMessage()));
                    break;
                case CLIENT_LEFT:
                    Platform.runLater(() -> cgui.removeClientFromClientList(message.getMessage()));
                    break;
                case CLIENT_CHANGED_USERNAME:
                    Platform.runLater(() -> cgui.renameClientFromClientList(message.getSender(), message.getMessage()));
                    break;
                case USERNAME_CHANGE_REQUEST:
                    setUsername(message.getMessage());
                    Platform.runLater(() -> cgui.getChatWindow().setTitle("Chat - " + getUsername()));
                    break;
                case CLIENT_TYPING:
                    break;
                case CLIENT_NOT_TYPING:
                    break;
                case CLIENT_SAW_MESSAGE:
                    break;
                }
            }
            Platform.runLater(() -> cgui.appendMessage("Die Verbindung zum Host wurde getrennt.", HPos.CENTER));
        }
        catch(Exception e)
        {
            Platform.runLater(() -> cgui.appendMessage("Die Verbindung zum Host wurde getrennt.", HPos.CENTER));
        } 
    }
}

0 个答案:

没有答案