最近学习java的nio socket非阻塞模式编程
服务器端发送信息格式如下: 8位的头部包含类型和信息的长度 如 LLWH002001234567890123456789,后面的信息中包含gb2312编码的汉字。
写客户端的时候碰到个问题:
SocketChannel的read(ByteBuffer[] dsts, int offset, int length)方法还没弄清楚怎么使用。
服务端发来 LLWH002001234567890123456789 这个消息时,用read(ByteBuffer dst) 这个方法读取到信息经常是分成好多段,
怎么才能把全部信息读取到ByteBuffer里头。
现在的代码如下:
public void Rec() throws IOException { int count; r_buff.clear(); count = sc.read(r_buff); r_buff.flip(); byte[] temp = new byte[r_buff.limit()]; r_buff.get(temp); System.out.println("reply is " + count + " long, and content is: " + new String(temp)); }