cor*_*iKa 8 java serialization
我需要通过套接字发送消息(来自用户的请求到引擎,以及从引擎到用户的响应).所以流程本质上是
+--------+ serialized request +--------+
| Server | <==== network ====> | Client |
+--------+ serialized response +--------+
^ ^
| request/response | mouse/keyclicks
| object |
v v
+--------+ +--------+
| Engine | | User |
+--------+ +--------+
Run Code Online (Sandbox Code Playgroud)
现在,在这里重新发明轮子才有意义.我正在处理双方的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);
}
Run Code Online (Sandbox Code Playgroud)
我没有关注的是,在我的服务器和客户端套接字中,我如何知道请求和响应的子类是什么?我看到了一种情况
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?
Run Code Online (Sandbox Code Playgroud)
我的第一个想法是通过字符串传递所有内容,但是当Java提供序列化时,这看起来有点傻.但是我怎样才能确定我知道哪个班级遇到了什么?就此而言,我是否需要知道,只要我只将UserRequest的后代发送到服务器并将EngineResponse发送给客户端?
只需使用instanceof提供的关键字:
Object o = in.readObject();
if (o instanceof SomeUserRequest)
{
SomeUserRequest sur = (SomeUserRequest)o;
..
}
else if (o instanceof OtherUserRequest)
{
..
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4609 次 |
| 最近记录: |