java:网络编程(客户端发送,服务器读取)

public class Client {
    public static void main(String[] args) throws IOException {
        SocketChannel sc = SocketChannel.open();
        // 客户端主动连接服务器(成功连接为0, 失败为-1)
        sc.connect(new InetSocketAddress("localhost", 8080));

        SocketAddress address = sc.getLocalAddress();
        sc.write(Charset.defaultCharset().encode("0123456789abcdef0000\n"));
        System.in.read();
    }
}
@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        // 使用 nio 理解阻塞模式
        // accept() 默认是阻塞方法,线程停止运行
        // Client建立连接(.connect())之后,accept() 恢复运行,线程继续执行
        // read() 默认是阻塞方法,线程停止运
        // Client发送数据(.write())之后,read() 恢复运行,线程继续执行

        // configureBlocking() ssc切换为非阻塞模式,线程继续运行
        // Client没有建立连接,accept() 返回null
        // configureBlocking() sc切换为非阻塞模式,线程继续运行
        // Client没有发送数据,read() 返回0

        // 1.创建selector, 管理多个channel
        Selector selector = Selector.open();

        // 创建服务器对象
        ServerSocketChannel ssc = ServerSocketChannel.open();

        // 切换非阻塞模式
        ssc.configureBlocking(false);

        // 2.建立selector和channel的联系(将channel注册到selector中)

        // SelectionKey 是将来事件发生后,通过它可以知道事件和哪个channel的事件
        SelectionKey sscKey = ssc.register(selector, 0, null);

        // sscKey只关注accept事件
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        log.debug("sscKey: " + sscKey);

        // 绑定监听端口
        ssc.bind(new InetSocketAddress(8080));

        while (true) {
            // 3.select方法, 没有事件发生,线程阻塞;有事件,线程恢复运行
            // 在事件未处理时,select不会阻塞, 事件发生后要么处理,要么取消(cancel())
            selector.select();

            // 将所有监听事件添加到未处理集合中(不会主动删除)
            Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
            // 4.处理事件
            while (iter.hasNext()) {
                SelectionKey key = iter.next();

                // 处理key时,需要从selectedKeys集合中删除
                // 移除迭代器返回的最后一个元素
                iter.remove();
                log.debug("key: " + key);

                // 5. 区分事件类型
                if (key.isAcceptable()) {
                    // key.channel() 得到是哪个channel的事件
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();

                    // 接收客户端的连接请求,建立连接,SocketChannel用来与客户端之间通信
                    SocketChannel sc = channel.accept();
                    log.debug("sc: " + sc);

                    // 切换非阻塞模式
                    sc.configureBlocking(false);

                    // 创建缓冲区
                    // 如果数据长度超过缓冲区长度,不报错,产生两次read事件,写入的是第二次读取的内容
                    // 应将ByteBuffer作为attachment关联到SelectionKey,每个
                    ByteBuffer buffer = ByteBuffer.allocate(16);

                    // 将channel注册到selector中
                    SelectionKey scKey = sc.register(selector, 0, buffer);
                    scKey.interestOps(SelectionKey.OP_READ);
                    log.debug("scKey: " + scKey);
                } else if (key.isReadable()) {
                    try {
                        SocketChannel channel = (SocketChannel) key.channel();

                        // 获取SelectionKey中的ByteBuffer
                        ByteBuffer buffer = (ByteBuffer) key.attachment();

                        // 获取客户端发送的数据
                        int read = channel.read(buffer);

                        // 客户端正常断开,read()返回-1
                        // 需要将selector注册的key删除
                        if (read == -1) {
                            key.cancel();
                        } else {
                            split(buffer);
                            // 如果没有读取到一个完整的内容,扩容
                            if (buffer.position() == buffer.limit()) {
                                ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity() * 2);
                                buffer.flip();
                                newBuffer.put(buffer);

                                // newBuffer替换原有的attachment
                                key.attach(newBuffer);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        // 客户端异常断开,产生一次read事件
                        // 需要将selector注册的key删除
                        key.cancel();
                    }
                }
            }
        }
    }

    private static void split(ByteBuffer source) {
        source.flip();
        // source.limit() 读的上限
        for (int i = 0; i < source.limit(); i++) {
            // get(i) 不会改变读索引的位置,'\n'占一个字节
            if (source.get(i) == '\n') {
                int length = i + 1 - source.position();

                // 将完整内容存入新的 ByteBuffer
                ByteBuffer target = ByteBuffer.allocate(length);

                // 从source读,向target写
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
                debugAll(target);
            }
        }
        source.compact();
    }
}
12:40:56 [DEBUG] [main] c.i.n.s.Server - sscKey: sun.nio.ch.SelectionKeyImpl@2b80d80f
12:40:59 [DEBUG] [main] c.i.n.s.Server - key: sun.nio.ch.SelectionKeyImpl@2b80d80f
12:40:59 [DEBUG] [main] c.i.n.s.Server - sc: java.nio.channels.SocketChannel[connected local=/127.0.0.1:8080 remote=/127.0.0.1:7645]
12:40:59 [DEBUG] [main] c.i.n.s.Server - scKey: sun.nio.ch.SelectionKeyImpl@649d209a
12:40:59 [DEBUG] [main] c.i.n.s.Server - key: sun.nio.ch.SelectionKeyImpl@649d209a
12:40:59 [DEBUG] [main] c.i.n.s.Server - key: sun.nio.ch.SelectionKeyImpl@649d209a
+--------+-------------------- all ------------------------+----------------+
position: [21], limit: [21]
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 30 31 32 33 34 35 36 37 38 39 61 62 63 64 65 66 |0123456789abcdef|
|00000010| 30 30 30 30 0a                                  |0000.           |
+--------+-------------------------------------------------+----------------+

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值