bfagundes
bfagundes

Reputation: 95

I Can't Send objects over sockets in Java

I have this problem, and I can't figure it out whats is wrong. I have searched on all over the internet, but without success.

So, I have to send an object over sockets in Java, and I can't figure out how to do it. I tried so many ways. I serialized the object, I tried to write the object directly. But nothing seems to work.

The detail is that I have a chat running in parallel. And sometimes when i open an ObjectOutputStream, or ObjectInputStream, I get busted in a deadlock. And I guess you guys could help me.

Its a hangman game where the clients connects to the server, and the server should send a random word, which is a object, to clients.

Server:

        try{
            socketConexao = socketRecepcao.accept();

    toClient = new DataOutputStream(socketConexao.getOutputStream());
    fromClient = new BufferedReader(new InputStreamReader(socketConexao.getInputStream()));

            //starts the chat
    Thread chat = new Thread(this);
    chat.start();

    }catch(IOException e){}

           //i dont really know how to send the object

    try{
        byte[] bytes = serialize(palavraSorteada);
        toClient.write(bytes);
    } catch (IOException e){
        e.printStackTrace();
    }

Client:

    socketCliente = new Socket(ip, port);

    toServer = new DataOutputStream(socketCliente.getOutputStream());
    fromServer = new BufferedReader(new InputStreamReader(socketCliente.getInputStream()));

            // starts the chat
    Thread chat = new Thread(this);
    chat.start();

    }catch(IOException e){System.exit (0);}

            // and dont really know how to receive the object

    try{
        ObjectInputStream os = new ObjectInputStream(socket.getInputStream());
        palavraSorteada = (Palavra) os.readObject();
        os.close();
    }catch(Exception e){
        e.printStackTrace();
    }

Upvotes: 0

Views: 1098

Answers (2)

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13525

In Server, split class Server in Server (accepts connections) and ServerConnection (separate thread). Place variables toClient and fromClient into ServerConnection. Now you spoil that variables when new client connects.

In Client, no need to start new Thread.

Upvotes: 0

Durandal
Durandal

Reputation: 20059

It should be fairly obvious what wrong here (from your description): You use one communication channel to send two different kinds of data. Since the receiving end can not predict what its going to receive you need to add information what comming next, so the receiving end knows what to do.

And probably noone is going to the trouble to figure out what your code fragments are really doing, reduce the fluff to what you want to ask about or even better make a one class copy&pasteable runnable example (as short as possible) that demonstrates the issue.

Upvotes: 1

Related Questions