Java NIO 网络编程

测试测试开发写给测试的测试软件该用什么测试软件去测试?
读完这个问题时你已经对 测 这个字感到陌生了

@Test
    void client() throws IOException {
        Path path = Paths.get("banner.txt");
        ByteBuffer buffer = ByteBuffer.allocate((int)path.toFile().length());
        FileChannel fc = FileChannel.open(path, StandardOpenOption.READ,
                StandardOpenOption.WRITE);
        /*使用SocketChannel连通服务端*/
        SocketChannel sc = SocketChannel.open(new InetSocketAddress("127.0.0.1",898));
        fc.read(buffer);
        buffer.flip();
        String s = new String(buffer.array(),0,buffer.limit());
        System.out.println(s);
        /*通道有内容写入时会交给服务端处理,此时客户端处于阻塞状态*/
        sc.write(buffer);
        /*等待服务端处理完毕后需关闭通道的写入,
        * 否则会一直保持连通*/
        sc.shutdownOutput();
        ByteBuffer buffer1 = ByteBuffer.allocate(12);
        sc.read(buffer1);
        buffer1.flip();
        String msg = new String(buffer1.array(),0,buffer1.limit());
        System.out.println(msg);

        sc.close();
        fc.close();
    }

    @Test
    void server() throws IOException {
        /*服务端通道*/
        ServerSocketChannel ssc = ServerSocketChannel.open();
        /*设置端口号*/
        ssc.bind(new InetSocketAddress(898));
        /*接收客户端通道,如果没有客户端消息可以接收则一直处于阻塞状态*/
        SocketChannel sc = ssc.accept();
        ByteBuffer buffer = ByteBuffer.allocate(1024*1024);
        FileChannel fc = FileChannel.open(Paths.get("bannerCopy.txt"),
                StandardOpenOption.WRITE,
                StandardOpenOption.READ,
                StandardOpenOption.CREATE);
        while (sc.read(buffer)!=-1){
            buffer.flip();
            fc.write(buffer);
            buffer.clear();
        }
        /*处理请求完毕后向客户端回复一个提示信息*/
        ByteBuffer buffer1 = ByteBuffer.allocate(12);
        /*注意,UTF-8字符集下每个中文字符占用三个字节*/
        buffer1.put("发送成功".getBytes());
        buffer1.flip();
        sc.write(buffer1);
        fc.close();
        ssc.close();
        sc.close();
    }


    /*非阻塞式NIO*/
    @Test
    void client1() throws IOException {
        SocketChannel sc = SocketChannel
                .open(new InetSocketAddress("127.0.0.1",880));
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put("fsdfsdfs".getBytes());
        buffer.flip();
        sc.write(buffer);
        sc.shutdownOutput();
        ByteBuffer buffer1 = ByteBuffer.allocate(1024*1024);
        sc.read(buffer1);
        buffer1.flip();
        System.out.println(new String(buffer1.array(),0, buffer1.limit()));
        sc.close();
    }

    /*使用多个客户端同时发送消息*/
    @Test
    void client2() throws IOException {
        new SocketChannelTest().client1();
    }

    @Test
    void server1() throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(880));
        /*利用线程池异步处理客户端提交的请求*/
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10,20,2,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue(),
                new ThreadPoolExecutor.DiscardPolicy()
                );
        ByteBuffer buffer = ByteBuffer.allocate(1024*1024*5);
        while (true){
            SocketChannel sc = ssc.accept();
             /*每有一个请求过来就直接提交给线程池去处理*/
            threadPool.submit(() -> {
                StringBuilder sb = new StringBuilder();
                while (true){
                    try {
                        if (!(sc.read(buffer)==-1)) {
                            break;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    buffer.flip();
                    sb.append(new String(buffer.array(),0,buffer.limit()));
                    buffer.clear();
                }
                ByteBuffer msg = ByteBuffer.allocate(12).put("发送成功".getBytes());
                msg.flip();
                try {
                    sc.write(msg);
                    System.out.println(sb);
                    sc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                
            });
        }
    }

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用 Java NIO(New I/O)进行网络编程的简单示例: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class NIOExample { public static void main(String[] args) throws IOException { // 创建一个线程池用于处理客户端连接 ExecutorService executor = Executors.newFixedThreadPool(10); // 创建 ServerSocketChannel 并绑定端口 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.bind(new InetSocketAddress("localhost", 8080)); System.out.println("Server started on port 8080"); while (true) { // 接受客户端连接 SocketChannel socketChannel = serverSocketChannel.accept(); // 使用线程池处理客户端连接 executor.execute(() -> handleClient(socketChannel)); } } private static void handleClient(SocketChannel socketChannel) { try { ByteBuffer buffer = ByteBuffer.allocate(1024); // 读取客户端发送的数据 int bytesRead = socketChannel.read(buffer); while (bytesRead != -1) { buffer.flip(); while (buffer.hasRemaining()) { System.out.print((char) buffer.get()); } buffer.clear(); bytesRead = socketChannel.read(buffer); } // 响应客户端 String response = "Hello from server"; ByteBuffer responseBuffer = ByteBuffer.wrap(response.getBytes()); socketChannel.write(responseBuffer); // 关闭连接 socketChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 这个示例创建了一个简单的服务器,监听本地的 8080 端口。当客户端连接时,会使用线程池处理连接,并读取客户端发送的数据。然后,服务器会向客户端发送 "Hello from server" 的响应,并关闭连接。 请注意,这只是一个简单的示例,实际的网络编程可能涉及更复杂的逻辑和处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值