使用数组和队列的方式解析字节

下面的逻辑为:从socket通道中读取到接收的数据到字节缓冲区,将缓冲区中的数据输出到字节的数据btyes中,再将数组中的数据一个个读取到字节队列bytesto 中(过来掉不需要的字节),最终

将bytesto 的数据转换到数组arr中,通过 new String(byte[] bytes, Charset charset)的方式将字节数据arr转换为指定字符集的字符串。(字符集转换的时候,一定要注意,有的时候一不小心就转为乱码了!)

 

// 返回为之创建此键的通道。
client = (SocketChannel) selectionKey.channel();
//将缓冲区清空以备下次读取
receivebuffer.clear();

//创建数据缓冲区receivebuffer 

  private   ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK);

 

//读取服务器发送来的数据到缓冲区中
count = client.read(receivebuffer);  // count 为缓冲字节的长度
if (count > 0) {
String receiveText = new String(receivebuffer.array(),0,count,"UTF-8");
// receiveText = new String(receivebuffer.array());
System.out.println("\r\n[接受到数据]:"+receiveText);

/**************************************************************/
receivebuffer.flip();
byte[] bytes = new byte[receivebuffer.remaining()];
receivebuffer.get(bytes);



// byte[] bytes= receiveText.getBytes();
// byte[] bytes=receiveText.getBytes("UTF-8");
List <Byte> bytesto = new LinkedList <Byte> ();
String msg="";
byte byteTemp = MLLP_START;
for(int i=0;i<bytes.length;i++){
byte[] b = new byte[1];
b[0]=bytes[i];
if(b != null && b.length > 0){
byteTemp = b[0];
}
if (byteTemp != MLLP_START && byteTemp != MLLP_END1)
{
bytesto.add (byteTemp);

}
}

byte[] arr = new byte[bytesto.size ()];
for (int i = 0; i < bytesto.size (); i++)
{
arr[i] = bytesto.get (i);
}
// msg = new String (arr, "GBK");
msg = new String (arr, "UTF-8");

ui.setMessage("从serverSocket获得信息:"+msg);
logger.info("从serverSocket获得信息:"+msg);
System.out.println("接收:"+msg); //处理消息内容

}

posted @ 2017-09-07 23:13  缺月疏桐  阅读(374)  评论(0编辑  收藏  举报