bfagundes
bfagundes

Reputation: 95

Java Receiving Objects over Sockets

I'm developing a hangman game for college. And it need to be over sockets, with server and clients. The game works fine by now.

But when its played by two people, trying to guess the same word, i need to know what letter one user choose, so i can disable that letter on the other user GUI.

So, i'm trying to send an letter object with an id that will disable the button on the other side, i'm sendind a message first, warning that i will send an object, so i don't get an exception.

Bur its only reading the first two objects that i send, on the third one i get an exception called java.io.StreamCorruptedException. Anyone knows why?

    Sending:
    toClient= new DataOutputStream(socketConection.getOutputStream());
    toClient.writeBytes("VK_Letra\n");
    objectToClient= new ObjectOutputStream(socketConetion.getOutputStream());
    objectToClient.writeObject(new Letter());
    objectToClient.flush();

    Receiving:
    fromServer = new BufferedReader(new InputStreamReader(socketCliente.getInputStream()));
    objectFromServer = new ObjectInputStream(socketCliente.getInputStream());

public void run(){
    String str;
    try{
        while(true){
            str = fromServer.readLine();

            if(str.equals("VK_Letter")){
                Letter l = (Letter) objectFromServer.readObject();
                System.out.println(l.getLetter());
                button[l.getId()].setEnabled(false);
            }else{
                chat.append(str+ "\n");
                chat.setCaretPosition(chat.getDocument().getLength());
            }
        }
    }catch(IOException | ClassNotFoundException e){
        JOptionPane.showMessageDialog(/* Error Message */);
    }
}

Upvotes: 1

Views: 264

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533472

A common source of confusion is when you mix different stream types on the same stream.

You have a fine example of two different problems.

  • You should not use multiple streams on the same stream e.g. DataOutptuStream and ObjectOutputStream
  • You should not mix binary and text streams such as BufferedReader and ObjectInputStream.

The solution is to use one, and only one, which suits your needs and use that.

Upvotes: 1

Richard Chambers
Richard Chambers

Reputation: 17573

The approach that I would use would be to have everything as an object so that you are only sending and receiving objects. Then the object would indicate the actual message along with any parameters or arguments or data.

You are mixing up between a read line and getting objects.

Upvotes: 1

Related Questions