networking - How do you send a User defined class object over a tcp/ip network connection in java? -


this example of user defined class i'd send client application server application:

class datastruct implements serializable{     byte data;     int messagenum;     public void setdata(byte datum, int messagenumber){         data=datum;         messagenum=messagenumber;     } } 

how send user defined class on tcp/ip connection in java?

what types of streams can use accomplish (if i'm sending more text)?

can pass full object via socket stream, or have cast after has been passed via stream?

i'm writing server/client application, , i've been able find tutorials examples of primitive types or strings being passed on network connection - not user defined types.

your , direction appreciated.

use objectoutputstream on sending side , objectinputstream on receiving side.

to bit more clear, here example (without exception handling).

sending side:

datastruct ds = ...; objectoutputstream oos = new objectoutputstream(socket.getoutputstream()); oos.writeobject(ds); oos.close(); 

receiving side:

objectinputstream ois = new objectinputstream(socket.getinputstream()); object o = ois.readobject(); if(o instanceof datastruct) {    datastruct ds = (datastruct)o;    // ds } else {    // gone wrong - should not happen if    // socket connected sending side above. } 

so yes, have cast @ receiving side compiler knows right class. (the casting not change class of object, changes compiler's knowledge of it.)

this serialization usable save objects file. of course, gives interoperability java, if have non-java partner, might want use custom serialization protocol, or xml-based format.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -