首页 > 编程语言 >Java NIO

Java NIO

时间:2023-04-15 22:11:42浏览次数:38  
标签:Java NIO java ByteBuffer clientChannel import SocketChannel nio

 

 

 Server 服务端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
 
public class NioServer {
    public static void main(String[] args) {
        try {
            // 创建ServerSocketChannel并打开Selector
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            Selector selector = Selector.open();
            // 绑定端口并注册接收连接事件
            serverSocketChannel.socket().bind(new InetSocketAddress(8080));
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("服务器已启动,监听端口8080...");
            // 处理Selector事件
            while (true) {
                if (selector.select(1000) == 0) {
                    // 没有事件发生,继续监听
                    continue;
                }
                // 处理发生的事件
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isAcceptable()) {
                        // 有新连接,注册读事件
                        ServerSocketChannel serverChannel = (ServerSocketChannel) selectionKey.channel();
                        SocketChannel clientChannel = serverChannel.accept();
                        clientChannel.configureBlocking(false);
                        clientChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                        System.out.println("客户端" + clientChannel.getRemoteAddress() + "已连接");
                    }
                    if (selectionKey.isReadable()) {
                        // 处理读事件
                        SocketChannel clientChannel = (SocketChannel) selectionKey.channel();
                        ByteBuffer buffer = (ByteBuffer) selectionKey.attachment();
                        clientChannel.read(buffer);
                        System.out.println("从" + clientChannel.getRemoteAddress() + "收到消息:" + new String(buffer.array(), 0, buffer.position()));
                    }
                    // 从ready集合中移除事件
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

client 客户端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
 
public class NioClient {
    public static void main(String[] args) {
        try {
            // 创建SocketChannel并连接
            SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8080));
            socketChannel.configureBlocking(false);
            // 向服务器发送消息
            ByteBuffer buffer = ByteBuffer.wrap("Hello, Server".getBytes());
            socketChannel.write(buffer);
            System.out.println("消息已发送:" + new String(buffer.array()));
            // 接收服务器返回的消息
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            while (socketChannel.read(readBuffer) == 0) {
                // 等待服务器响应
            }
            System.out.println("收到服务器响应:" + new String(readBuffer.array(), 0, readBuffer.position()));
            // 关闭连接
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

 

参考:

标签:Java,NIO,java,ByteBuffer,clientChannel,import,SocketChannel,nio
From: https://www.cnblogs.com/xiaomu2023/p/17322037.html

相关文章

  • JavaWeb
    本篇文章是我在学习尚硅谷的JavaWeb视频视频做的学习笔记,尚硅谷的JavaWeb视频讲的很详细,欢迎去观看https://www.bilibili.com/video/BV1Y7411K7zz/?spm_id_from=333.337.search-card.all.click&vd_source=f38047c43021f07cf7a4e84b564bde02目录一、HTML和CSS1.1B/S软件的结构1......
  • Java | 一分钟掌握JDK命令行工具 | 3 - 实战
     作者:Mars酱 声明:本文章由Mars酱编写,部分内容来源于网络,如有疑问请联系本人。 转载:欢迎转载,转载前先请联系我!前言前一篇Java|一分钟掌握JDK命令行工具|2-分类-掘金(juejin.cn)罗列了一些JDK命令行工具,我们没有必要把所有命令行工具全部介绍,那样对于开发者来说不实用也......
  • java字节码编程技术(8/10) -Javassist
    Javassist这个库和asm经常使用,它的性能稍差一点<dependency><groupId>org.javassist</groupId><artifactId>javassist</artifactId><version>3.27.0-GA</version></dependency>获取一个类加载器(ClassLoader),以加载指定的.jar或.class文件privateClassLoade......
  • java.lang.NoSuchMethodException: com.innovation.web.BuyServlet.get(javax.servlet
    问题描述我将路径定义到相应的servlet的函数方法里面,然后就出现了这个问题,很明显的找不到相应的函数方法;问题解决将目光重新放到我定义的相关路径那里,发现我出于习惯,将servlet里面原本应该是名为checkIt的函数方法写成了get方法,改回去之后,这个问题也就解决啦!......
  • Java Stream API 操作完全攻略:让你的代码更加出色 (四)
    前言  JavaStream是一种强大的数据处理工具,可以帮助开发人员快速高效地处理和转换数据流。使用Stream操作可以大大简化代码,使其更具可读性和可维护性,从而提高开发效率。本文将为您介绍JavaStream操作的所有方面,包括range、range、iterate、generate等操作,让你的代码行......
  • eclpise断点调试Java代码
    Eclipse支持对Java代码进行Debug也就是在执行代码时暂停执行并可以观察相关的信息,比如栈中的变量,堆中的变量,执行的代码,方法调用栈等,这个暂停的位置就是断点一个简单的工程如果需要观察getMax方法的执行,可以在代码编辑器左边缘双击,增加断点,或者右键ToggleBre......
  • java -- 标记接口
    标记接口标记接口(MarkerInterface),又称标签接口(TagInterface)仅代表一个标记不包含任何方法标记接口是用来判断某个类是否具有某种能力Cloneable标记接口此类实现了Cloneable接口,以指示Object.clone方法可以合法地对该类实例进行按字段复制如果在没有实现Cloneable接......
  • JAVA远程请求工具类
    importcom.alibaba.fastjson.JSONObject;importorg.apache.http.Consts;importorg.apache.http.HttpResponse;importorg.apache.http.HttpStatus;importorg.apache.http.NameValuePair;importorg.apache.http.client.entity.UrlEncodedFormEntity;importorg.apac......
  • Java笔记(16) Collection集合-->Set集合-->HashSet
    1.Set接口基本介绍Set是无序集合(添加和取出的顺序不一致,但取出的顺序是固定的),没有索引不允许重复元素,所以最多包含一个nullJDKAPI中Set接口的实现类有:Abstract,ConcurrentHashMap.KeySetView,ConcurrentSkipListSet,CopyOnWriteArraySet,EnumSet,HashSet,JobStateRea......
  • java的协变和逆变
    一、协变和逆变的概念协变:模板中赋值给A的是A或者A的子类。比如:List<?extendsA>listA=List<ChildA>()即:ChildA可能是A或者A的子类逆变:模板中赋值给A的是A或者A的父类。比如:List<?superA>listA=List<ParentA>()即: ParentA可能是A或者A的父类二、为何会有协变和逆......