以服务器为例,服务器接收到客户端消息:可以分为三类。
1.服务器与客户端基本互动
服务器接收到客户端,要理解对方消息前,必须约定通信方式,即信息必须加上双方理解的通信标记ECammand。
2.客户端调远程用服务器方法。
在理解客户端消息基础上,就可实现客户端远程调用。那么就需要标记具体调用方法action。
3.客户端对客户端消息转发
转发消息前提,需要知道目标地址,所以加入地址标记。
4.NetMessage
NetMessage 实现1、2、需求。
public class NetMessage {
private ECammand cammand;
private String action;
private String message;
}
4.1 消息装箱处理
@Override
public String toString() {
return cammand + ":" + action + ":" + message;
}
4.2消息拆箱处理
public NetMessage(String info) {
int index = info.indexOf(":");
String cammand = info.substring(0, index);
String subInfo = info.substring(index + 1);
index = subInfo.indexOf(":");
action = subInfo.substring(0,index);
message = subInfo.substring(index + 1);
this.cammand = ECammand.valueOf(cammand);
}
5.Interactive
Interactive针对3需求,将NetMessage再包装后,加入源地址,及目标地址。
package edu.xupt.cs.core;
public class Interactive {
private String sourceId;
private String targetId;
private String message;
public String getSourceId() {
return sourceId;
}
public String getMessage() {
return message;
}
public Interactive setMessage(String message) {
this.message = message;
return this;
}
public Interactive setSourceId(String sourceId) {
this.sourceId = sourceId;
return this;
}
public String getTargetId() {
return targetId;
}
public Interactive setTargetId(String targetId) {
this.targetId = targetId;
return this;
}
}