我需要通过套接字发送消息(从用户到引擎的请求,以及从引擎到用户的响应)。所以流程本质上是
+--------+ 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);
}
我没有遵循的是,在我的服务器和客户端套接字中,我如何知道请求和响应的子类正在进入?我看到这样的情况
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 发送到客户端?
只需使用instanceof
提供的关键字:
Object o = in.readObject();
if (o instanceof SomeUserRequest)
{
SomeUserRequest sur = (SomeUserRequest)o;
..
}
else if (o instanceof OtherUserRequest)
{
..
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)