为了账号安全,请及时绑定邮箱和手机立即绑定

NIO异常java.nio.BufferUnderflowException

NIO异常java.nio.BufferUnderflowException

德玛西亚99 2019-03-01 10:38:37
package client; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.concurrent.TimeUnit; public class NioClient { public static void main(String[]args){ ByteBuffer buffer = ByteBuffer.allocate(1024); SocketChannel socketChannel = null; ByteBuffer res=ByteBuffer.allocate(1024); try { socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.connect(new InetSocketAddress("localhost",8080)); if(socketChannel.finishConnect()) { int i=0; int size=0; while(true) { TimeUnit.SECONDS.sleep(1); String info = "I'm "+i+++"-th information from client"; buffer.clear(); buffer.put(info.getBytes()); buffer.flip(); while(buffer.hasRemaining()){ // System.out.println(buffer); socketChannel.write(buffer); } size=socketChannel.read(res); while((size)!=0){ res.flip(); byte result[]=new byte[size]; res.get(result); System.out.println(new String(result)); res.clear(); } } } } catch (IOException | InterruptedException e) { e.printStackTrace(); } finally{ try{ if(socketChannel!=null){ socketChannel.close(); } }catch(IOException e){ e.printStackTrace(); } } } } 解决方法:将while循环上的赋值放到while循环里 while((size=socketChannel.read(res))!=0){ 为什么会这样,求解释??? 另附赠服务端代码 package client; import java.io.*; import java.net.*; import message.IMessage; import message.LoginMessage; public class Server2 { public static void main(String[] args) throws IOException { Server2 socketService = new Server2(); socketService.oneServer(); } public void oneServer() { ServerSocket serverSocket = null; InputStream in=null; OutputStream out =null; try { System.out.println(" server start"); serverSocket = new ServerSocket(8080); int Size = 0; byte[] res = new byte[1024]; while(true){ Socket clntSocket = serverSocket.accept(); SocketAddress clientAddress = clntSocket.getRemoteSocketAddress(); System.out.println("Handling client at "+clientAddress); in = clntSocket.getInputStream(); out=clntSocket.getOutputStream(); int i=0; while((Size=in.read(res))!=-1){ byte[] temp = new byte[Size]; System.arraycopy(res, 0, temp, 0, Size); System.out.println(new String(temp)); String status="success"+i; i++; out.write(status.getBytes()); out.flush(); } } } catch (IOException e) { e.printStackTrace(); } finally{ try{ if(serverSocket!=null){ serverSocket.close(); } if(in!=null){ in.close(); } }catch(IOException e){ e.printStackTrace(); } } } }
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 1869 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号