首页 > 代码库 > 无题2
无题2
package nio; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class SocketChannelDemo { public static void main(String[] args) { // TODO Auto-generated method stub try { SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999)); ByteBuffer bb = ByteBuffer.allocate(48); int byteNum; int bytes = socketChannel.read(bb); bb.flip(); while (bb.hasRemaining()) { System.out.print((char) bb.get()); } bb.clear(); socketChannel.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package nio; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; public class ServerSocketChannelDemo { public static void main(String[] args) { try { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(9999)); String msg = "send something to you"; ByteBuffer bb = ByteBuffer.allocate(48); bb.clear(); bb.put(msg.getBytes()); bb.flip(); while (true) { SocketChannel socketChannel = ssc.accept(); while (bb.hasRemaining()) { socketChannel.write(bb); } socketChannel.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
我一直在想为什么socket客户端只能读一次或得返回信息,原来是我server端写错了,应该把设置byteBuffer内容的这段代码写在 while循环里
如下:
while (true) { SocketChannel socketChannel = ssc.accept(); String msg = "send something to you"; ByteBuffer bb = ByteBuffer.allocate(48); bb.clear(); bb.put(msg.getBytes()); bb.flip(); while (bb.hasRemaining()) { socketChannel.write(bb); } // socketChannel.close(); }
无题2
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。