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();
}