(I know this can be done in RMI, but I need to do this using sockets since I found there could be some setup process if RMI methods used)
Please have a look at the simple Client-Server code at http://www.coderanch.com/t/205325/sockets/java/send-any-java-Object-through
In this program, the order two objects sent by SimpleServer are known by SimpleClient.
i.e: Server
oos.writeObject(new testobject(1,"object from client"));
oos.writeObject(new String("another object from the client"));
Client does开发者_如何学C the casting according to the order the object is received.But I want to avoid this nature and make client send any object at any time so the server should also be able to handle each object sent accordingly and return a result.
testobject to = (testobject)ois.readObject();
System.out.println(to.id);}
System.out.println((String)ois.readObject());
Is there a way to "label" the objects being sent so that the action can be determined by a simple "if" statement in Server?
OR
is there a better way to use a ResultSet returned by the Server instead of my object serializing approach?
thanks in advance.
Thanks
readObject
will return an object in its proper class. if you need to have some branching logic based on that you can use instanceof
:
Object newObj = stream.readObject();
if (newObj instanceof testobject) {
doSomething((testobject) newObj);
} else if (newObj instanceof String) {
doSomethingWithString((String) newObj);
} // etc.
As a rule, this is not recommended for all objects read from a stream. If you're going to use ObjectStreams to establish a protocol, you should document it and stick to it. That way, if one side sends incorrect data, you'll catch it more quickly on the other side.
However, in a scenario where at a given point in the protocol flow, it's expected that the client might be sending one of several different types of objects, then it might make sense.
精彩评论