Netty 网络 阻塞模式

本文介绍了使用JavaNIO(Non-blockingI/O)在服务端创建SocketChannel,处理客户端连接并读取数据,以及如何解决单线程阻塞问题。通过ServerSocketChannel的accept()和SocketChannel的read()方法展示了并发连接的处理方式。
摘要由CSDN通过智能技术生成

1.概要

1.1 需求

服务端等待连接,等待读取数据,客户端写入数据。

1.2 要点

  • SocketChannel sc = ssc.accept();
  • channel.read(byteBuffer);

1.3 要点说明

因为两处都是阻塞模式,所以用一个线程很难处理多个客户端同时访问的情况。

2.代码

2.1 服务端

package com.xjc.springcloundtest;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.net.SocketOption;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class Main {
    public static void main(String[] args) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(16);
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));
        List<SocketChannel> channels = new ArrayList<>();
        while (true){
            System.out.println("accept 前");
            SocketChannel sc = ssc.accept();
            System.out.println("accept 后");
            channels.add(sc);
            for (SocketChannel channel: channels){
                System.out.println("read 后");
                channel.read(byteBuffer);
                byteBuffer.flip();
                while (byteBuffer.hasRemaining()){
                    byte b = byteBuffer.get();
                    System.out.println((char)b);
                }
                byteBuffer.clear();
                System.out.println("read 后");
            }
        }
        //System.out.println("Hello world!");
    }
}

2.2 客户端

package com.xjc.springcloundtest;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;

public class Client {
    public static void main(String[] args) throws IOException {
        SocketChannel sc = SocketChannel.open();
        sc.connect(new InetSocketAddress("localhost", 8080));
        System.out.println("Hello world!");
    }
}

2.3 客户端debug模式下发送数据 

sc.write(Charset.defaultCharset().encode("hello") 

3 运行结果

3.1 服务端

accept 前

3.2 客户端

Hello world!

Process finished with exit code 0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值