假设我们的tcp命令 定义如下:SayHello() SayWorld()
我们在接收到这些信息后,可以用enum来区分不同的命令。
方法是利用正则表达式,循环和枚举类型去比对。
CommandToken
public enum CommandToken {
SayHello(1, makePattern("SayHello"), "说hello"),
SayWorld(2, makePattern("SayWorld"), "说world");
private int value; //命令值
private Pattern pattern; //匹配模式
private String description; //命令描述
private CommandToken(int value, Pattern pattern, String descripton) {
this.value = value;
this.pattern = pattern;
this.description = descripton;
}
public int getValue() {
return value;
}
public Pattern getPattern() {
return pattern;
}
public String getDescription() {
return description;
}
/**
* 解析命令类型
* @param value
* @return
*/
public static CommandToken parse(String value) throws Exception{
CommandToken[] vs = values();
for (CommandToken s : vs) {
if (s.pattern.matcher(value).matches()) {
return s;
}
}
if (value.length() > 200) {
value = value.substring(0, 200) + "...";
}
throw new Exception("未知命令:" + value);
}
/**
* 生成Pattern
* @param key
* @return
*/
private static Pattern makePattern(String key) {
return Pattern.compile("\\b" + key + "\\s*\\([^\\)]*\\)");
}
@Override
public String toString() {
return description;
}
}
调用方式
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
final String msg = ((String) message).trim();
if(msg.length() <= 500) {
logger.debug("Receive TCP << " + msg);
}
else {
logger.debug("Receive TCP << " + msg.substring(0, 500) + "...");
}
CommandToken token = null;
try {
//解析设备发来的命令
token = CommandToken.parse(msg);
}
catch (Exception e) {
logger.error(e.getMessage());
session.closeNow();
return;
}
String out = null;
switch(token) {
case SayHello:
out = "Hello";
break;
case SayWorld:
out = "World";
break;
}
if(out == null) {
session.closeNow(); //关闭连接
}
else {
session.write(out);
logger.debug("Send TCP >> " + out);
}
}