tcp - Sending different objects to Server in Java -
tcp - Sending different objects to Server in Java -
i have couple of classes. student, teacher , book.
i want send instances of 3 objects server connecting client. know how send/receive instances of single type, i.e. pupil server client using next code
client side
socket socket = new socket(ip, port); seek { objectinputstream objectinput = new objectinputstream(socket.getinputstream()); seek { object object =(student) objectinput.readobject(); pupil std = (student) object; //do std } grab (classnotfoundexception e) { e.printstacktrace(); }
server side
pupil = new student(); serversocket myserversocket = new serversocket(port); socket skt = myserversocket.accept(); seek { objectoutputstream objectoutput = new objectoutputstream(skt.getoutputstream()); objectoutput.writeobject(a); } grab (ioexception e) { e.printstacktrace(); }
how extend code able send different types of objects server , receive them correctly on client side
do need wrap them in object , give each 1 type? thanks!
do need wrap them in object , give each 1 type?
it improve design create class aggregate object instances. prevent bugs , result in much more readable code.
if want exchange plain java objects between client , server improve off using remote method invocation (examples included in article).
how extend code able send different types of objects server?
if insist on learning sockets can send , receive object instances 1 after other.
you can send arrays of objects.
client example:
public class client { public static void main(string[] args) throws ioexception { socket socket = new socket("127.0.0.1", 6060); seek { objectinputstream objectinput = new objectinputstream(socket.getinputstream()); pupil student = (student)objectinput.readobject(); system.out.println("received pupil (" + pupil + ")"); objectinput = new objectinputstream(socket.getinputstream()); teacher teacher = (teacher) objectinput.readobject(); system.out.println("received teacher (" + teacher + ")"); //do std } grab (classnotfoundexception e) { e.printstacktrace(); } { socket.close(); } } }
server example:
public class server { public static void main(string[] args) throws ioexception { serversocket myserversocket = new serversocket(6060); system.out.println("up , running"); socket skt = myserversocket.accept(); seek { pupil student = new student(); objectoutputstream objectoutput = new objectoutputstream(skt.getoutputstream()); objectoutput.writeobject(student); system.out.println("sent student"); teacher teacher = new teacher(); objectoutput = new objectoutputstream(skt.getoutputstream()); objectoutput.writeobject(teacher); system.out.println("sent teacher"); } grab (ioexception e) { e.printstacktrace(); } { myserversocket.close(); } system.out.println("shutting down"); } }
but approach hard understand , bug prone, because if don't order right on both client
, server
code won't work.
java tcp client-server inputstream
Comments
Post a Comment