码迷,mamicode.com
首页 > 其他好文 > 详细

无题2

时间:2016-12-17 14:31:37      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:lin   and   客户端   art   isp   .so   except   ring   ack   

技术分享
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();
        }

    }

}
View Code
技术分享
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();
        }

    }
}
View Code

我一直在想为什么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

标签:lin   and   客户端   art   isp   .so   except   ring   ack   

原文地址:http://www.cnblogs.com/jarman/p/6189561.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!