I have a multithread server, waiting for socket connections.
The first exchange of message is always of the same type, the clients sends an object with the authentication details(userid/pwd), the server checks it and reply to the server if the authentication has been passed or not.
After this first exchange of messages, the client will send some requests, corresponding to various tasks the server is able to execute.
How do i model those eterogeneous requests? In particular my question regards the type of object sent between client and server with InputObjecStream/OutputObjectStream
I had 2 ideas:
-
Using a “generic message” object, with 2 attributes: a task identifier and an HashMap without generics, able to carry various type of parameters requested for executing the task.
-
An object for every type of task, this solution is “cleaner”, but I don’t know how to make the server understand the type of the message received, I thought about a series of object casting of the received message from the client to every possible “specific task message”, ignoring the many CastException. It sounds just bad, is there any way to avoid this?
The first approach is very generic but will be hard to maintain. After a while you’ll notice that you no longer remember what kind of objects should be in this generic map. You’ll have to keep the dictionary in sync.
The second approach is much better. Essentially you receive an abstract
Requestobject with various subclasses. The base class can hold some general information. Normally you would use polymorphism and implement the action in each subclass, overriding abstract method fromRequestclass. But you can’t because request object would have to hold server-side logic.The best you can do here is visitor design pattern. With it, for the price of slightly obscuring your code, you’ll get very generic and safe design.
instanceoftends to be ugly after some time.