简体   繁体   中英

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

This is an example of a user defined class I'd like to send from a client application to a server application:

class dataStruct implements Serializable{
    byte data;
    int messageNum;
    public void setData(byte datum, int messageNumber){
        data=datum;
        messageNum=messageNumber;
    }
}

How do you send a user defined class over a tcp/ip connection in java?

What types of streams can I use to accomplish this (if I'm sending more than just text)?

Can I pass a full object via a socket stream, or will I always have to cast it after it has been passed via a stream?

I'm writing a server/client application, and I've only been able to find tutorials with examples of primitive types or strings being passed over a network connection - not user defined types.

Your help and direction are greatly appreciated.

Use an ObjectOutputStream on the sending side and an ObjectInputStream on the receiving side.

To be a bit more clear, here is an example (without any 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;
   // do something with ds
}
else {
   // something gone wrong - this should not happen if your
   // socket is connected to the sending side above.
}

So yes, you have to cast at the receiving side so the compiler knows the right class. (The casting does not change the class of the object, only changes the compiler's knowledge of it.)

This Serialization is also usable to save objects to a file. Of course, this gives only interoperability to Java, if you have a non-Java partner, you might want to use a custom serialization protocol, or some XML-based format.

Let the objects implement the Serializable marker interface, and then transfer the objects using ObjectOutputStream and ObjectInputStream . When the object comes out on the other end, it will be via the readObject() method on ObjectInputStream , which returns Object , so yes, you will need to cast it to the proper type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM