我需要通过套接字发送消息(用户向引擎发送请求和引擎向用户发送响应)。因此,流程基本上是这样的:
+--------+ serialized request +--------+
| Server | <==== network ====> | Client |
+--------+ serialized response +--------+
^ ^
| request/response | mouse/keyclicks
| object |
v v
+--------+ +--------+
| Engine | | User |
+--------+ +--------+
现在,在这里不重新造轮子是有意义的。我正在处理双方的Java,因此我计划像这样使用对象:
/**
* A Client makes a Request.
*/
abstract class UserRequest implements Serializable {
/**
* The engine will call request.engineCallback(this);
* This will tell the Engine what the request is, at which point
* the Engine will determine its response.
*/
abstract EngineResponse engineCallback(Engine engine);
}
/**
* The Engine has calculated a Response.
*/
abstract class EngineResponse implements Serializable {
/**
* The User will call response.userCallback(this);
* This tells the User what the Engine thought of its request,
* and what happened as a result.
*/
abstract void userCallback(User user);
}
我不理解的是,在我的服务器和客户端套接字中,我怎样才能知道什么子类的 Request 和 Response 正在到达?我看到了这样的情况:
Object request = in.readObject();
// now what? How do I know what to cast it to?
// Can I just cast it like
UserRequest request = (UserRequest)(in.readObject());
engine.addToRequestQueue(request); // let it take care of implementation details?
我的第一个想法是通过字符串传递一切,但是当Java提供序列化时,这似乎有点傻。但是我如何确保知道通过线路传输的是哪个类?说到这个问题,只要我只将UserRequest的后代发送到服务器并将EngineResponse发送到客户端,我需要知道吗?
engine.addToRequestQueue(request)
- 这是一个被接受的做法吗?我不在乎你给我什么类型的Request,我只是会在我的引擎中使用它的回调方法。 - corsiKainstanceof
会起作用,所以我很高兴我坚持问了我的问题。(当你写了两页纸,你不想只是不发帖子,对吧?) - corsiKa