java - incompatible types : object cannot be converted to ChatData -
java - incompatible types : object cannot be converted to ChatData -
i new java , trying exchange objects between client , server using readobject() showing incompatible types : object cannot converted chatdata
. why did error occurred , how resolve this. please tell me how works.
` socket socket = new socket("127.0.0.1", 3000); objectoutputstream clientwriter; objectinputstream clientreader; seek { clientwriter = new objectoutputstream(socket.getoutputstream()); clientreader = new objectinputstream(socket.getinputstream()); chatdata clientoutputdata = new chatdata("hello! message client number ", socket.getinetaddress()); clientwriter.writeobject(clientoutputdata); chatdata clientinputdata = clientreader.readobject(); //here error , chatdata class. seek { // processing thread.sleep(2000); } grab (interruptedexception ex) { logger.getlogger(chatclient.class.getname()).log(level.severe, null, ex); } } grab (ioexception ex) { logger.getlogger(chatclient.class.getname()).log(level.severe, null, ex); } { seek { if (clientreader != null) { clientreader.close(); } if (clientwriter != null) { clientwriter.close(); } socket.close(); } grab (ioexception ex) { system.err.println("couldn't close connection succesfully"); logger.getlogger(chatclient.class.getname()).log(level.severe, null, ex); } } thread.sleep(15000); } }
readobject() method returns object of type object.
you have convert received object type want.
chatdata clientinputdata = clientreader.readobject(); //here error , chatdata class.
solution:
chatdata clientinputdata = (chatdata) clientreader.readobject();
you should check if received object of type want, otherwise classcastexception thrown.
object clientinputdata = clientreader.readobject(); chatdata convertedchatdata = null; if(clientinputdata instanceof chatdata) { convertedchatdata = (chatdata) clientinputdata; }
java sockets
Comments
Post a Comment