登录 之 服务端响应(二)

2014-11-24 11:36:21 · 作者: · 浏览: 28
= serverChanel.accept();
sc.configureBlocking(false);
// 把新连接注册到选择器
sc.register(selector,SelectionKey.OP_READ);
it.remove();
} else {
// 读客户端数据的事件,此时有客户端发数据过来,客户端事件
if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
// 读取数据
SocketChannel sc = (SocketChannel) key.channel();
if (sc.read(echoBuffer) > 0) {
echoBuffer.flip();
//System.out.println("limit:" + echoBuffer.limit());
byte[] content = new byte[echoBuffer.limit()];
echoBuffer.get(content);
String result = new String(content);
doPost(result, sc);
}
echoBuffer.clear();
it.remove();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public void doPost(String str, SocketChannel sc) {
int firstIndex = str.indexOf(SPLITSTR);
int secondIndex = str.lastIndexOf(SPLITSTR);
String result = "";
if (firstIndex > 0) {
String name = str.substring(0, firstIndex);
String pswd = str.substring(firstIndex + SPLITSTR.length(),
secondIndex);
String respondStyle = str.substring(secondIndex + SPLITSTR.length());
if (name.length() != 0 && pswd.length() != 0 && respondStyle.length() != 0) {
switch (this.htMap.get(respondStyle)) {
case 1: // response of land
if (validateLogOn(name, pswd)) {
try {
result = ISACK + SPLITSTR
+ this.getLogOnUserInfo().getString("SName");
} catch (SQLException e) {
e.printStackTrace();
}
} else
result = ISNAK + SPLITSTR + "userName or passwd error";
break;
case 2: // response of register
if (validateUserExist(name)){
result = ISNAK + SPLITSTR + name + " has existed";
}else {
if (registerUserInfo(name, pswd)){
result = ISACK + SPLITSTR + name;
}else result = ISNAK + SPLITSTR + "regist " + name + " failed";
}
break;
default:
System.out.println("No response to [" + respondStyle + "].");
System.exit(1);
break;
}
} else {
System.out.println("At least one value of [name,passwd,respondStyle] is null.");
System.exit(1);
}
} else {
System.out.println("Can not receive split string.");
System.exit(1);
}
ByteBuffer bb = ByteBuffer.allocate(result.length() + 10);
bb.put(result.getBytes());
bb.flip();
try {
sc.write(bb);
} catch (IOException e) {
e.printStackTrace();
}
bb.clear();
}
private boolean validateLogOn(String name,String passwd){
connpool=