StringBuffer sb=new StringBuffer();
while (buffer.hasRemaining()) {
b = buffer.get(); if (b != 0) {
sb.append((char)b);
}
}****************************************
如上,Socket服务器端读取数据,通过一个一个的字符来读,如果字符是\0,就算读完了一个XML格式的字符串。因为客户端发过来是通过\0结束的。\0转换成字节就是0。能不能一次读取一行,或是一次读取从这个\0到另一个\0结束的字符串???
while (buffer.hasRemaining()) {
b = buffer.get(); if (b != 0) {
sb.append((char)b);
}
}****************************************
如上,Socket服务器端读取数据,通过一个一个的字符来读,如果字符是\0,就算读完了一个XML格式的字符串。因为客户端发过来是通过\0结束的。\0转换成字节就是0。能不能一次读取一行,或是一次读取从这个\0到另一个\0结束的字符串???
ByteBuffer buffer = ByteBuffer.allocate(1024);
* 接收消息
* @param sc SocketChannel
* @return boolean
*/
private synchronized boolean acceptInfo(SocketChannel sc) { StringBuffer sb = new StringBuffer();
int b = 0;
ByteBuffer buffer = ByteBuffer.allocate(1024);
byte[] myByte = new byte[0]; buffer.clear();
try {
//数据读入buffer
while (sc.read(buffer) > 0) {
buffer.flip(); //如果为0则返回
if (buffer.limit() == 0) {
return false;
}
sb.append(new String(myByte, "utf-8"));
myByte = new byte[buffer.limit()]; //根据缓冲区的字节数初始化大小。
int t = 0; /**
* 以下逐个读取字符
*/
while (buffer.hasRemaining()) {
b = buffer.get(); if (b != 0) {
myByte[t] = (byte) b;
t++;
}
else {
sb.append(new String(myByte, "utf-8"));
String line = sb.toString().trim();
/**
* 如果接收值为空或为null,则返回。
*/
if (line.equals("")) {
return false;
}
else {
/**
* 开始处理接收到的消息63 1 7
*/
Message.createNewMessage(sc, line); setAcceptInfo(line);
line = null;
t = 0; return true;
} //end if
} //end if
} //end while
buffer.clear();
} //end while
}
catch (IOException ie) {
lg.info("读取数据出错:" + ie.getMessage());
return false; //如果出错则返回
}
return false; //成功返回
}
虽然是一个一个的读,但是因为数据在本地内存里,效率不会低,并且你还要判读“\0”,所以一个个的读也是必须的。java.io.BufferedReader有readLine()方法,它也是一个一个判断的。不过它是先读到一个本地数组里面,使用[]遍历,找到"\n"。因为是[],可能效率会高一点。ByteBuffer可以批量获得一个byte[],你可以从这个byte[]中判断“\0”,这样效率会高一点?