当前位置: 首页 > news >正文

一个用java的NIO实现的socket的客户端和服务端的demo

这个demo没有使用selector,无法使用一个单线程很好的处理多个channel的消息,性能没有使用selector高

服务端

public class Server {
    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverS = ServerSocketChannel.open();
        serverS.bind(new InetSocketAddress(8080));
        ByteBuffer inB = ByteBuffer.allocate(1024);
        ByteBuffer outB = ByteBuffer.allocate(1024);
        while(true){
            SocketChannel accept = serverS.accept();
            MsgHandler.sendMsg(outB, "你好,客户端,连接建立成功", accept);
            while(accept.read(inB) != -1){
                String msg = MsgHandler.receiveStrMsg(inB, accept);
                System.out.println(msg);
                MsgHandler.sendMsg(outB, "消息处理完毕,from服务器",accept);
            }
        }
    }
}

客户端

public class Client {
    public static void main(String[] args) throws Exception {
        SocketChannel clientC = SocketChannel.open();
        Scanner scanner = new Scanner(System.in);
        clientC.connect(new InetSocketAddress("localhost",8080));
        clientC.configureBlocking(false);
        ByteBuffer outB = ByteBuffer.allocate(1024);
        ByteBuffer inB = ByteBuffer.allocate(1024);
        while(true){
            while(clientC.read(inB) > 0){
                System.out.println(MsgHandler.receiveStrMsg(inB, clientC));
            }
            String msg = scanner.next();
            MsgHandler.sendMsg(outB, msg, clientC);
            if(msg.equals("exit")){
                clientC.close();
                return;
            }
        }
    }
}

消息处理类

public class MsgHandler {
    public static void sendMsg (ByteBuffer outB, String msg, SocketChannel channel){
        try {
            outB.put(msg.getBytes("UTF-8"));
            outB.flip();
            while(outB.hasRemaining()){
                channel.write(outB);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            outB.clear();
        }
    }
    public static String receiveStrMsg(ByteBuffer inB, SocketChannel channel){
        List<Byte> bList = new ArrayList<>();
        String msg = null;
        try {
            inB.flip();
            while(inB.hasRemaining()){
                bList.add(inB.get());
            }
            byte[] bytes = new byte[bList.size()];
            for(int i = 0;i < bList.size();i++){
                bytes[i] = bList.get(i);
            }
            msg = new String(bytes, "UTF-8");
        }
        catch (Exception e){
            e.printStackTrace();
        }finally {
            inB.clear();
            return msg;
        }
    }
}

 

相关文章:

  • 使用java的nio的pipe实现两个线程间传送数据的demo
  • org.hibernate.TransactionException: nested transactions not supported异常
  • elasticsearch
  • rancher简介
  • InfluxDB+cAdvisor+Grafana容器管理
  • serviceComb[No schema defined for start.servicecomb.io:]异常
  • ServiceComb
  • kubernetes
  • 生产报redis连接满的问题
  • 一、Linux入门简述
  • 二、Linux入门之文件管理及相关命令
  • 3、Linux命令小例:用户权限管理、ls、cp、tr
  • 三、Linux入门之标准I/O重定向、管道、用户管理
  • 三、Linux入门之文件权限
  • 二、Linux入门之VIM编辑器
  • JavaScript设计模式系列一:工厂模式
  • JavaScript新鲜事·第5期
  • JS+CSS实现数字滚动
  • Laravel深入学习6 - 应用体系结构:解耦事件处理器
  • Linux快速复制或删除大量小文件
  • Python进阶细节
  • vue自定义指令实现v-tap插件
  • Vultr 教程目录
  • 包装类对象
  • 对话:中国为什么有前途/ 写给中国的经济学
  • 简单实现一个textarea自适应高度
  • media数据库操作,可以进行增删改查,实现回收站,隐私照片功能 SharedPreferences存储地址:
  • 400多位云计算专家和开发者,加入了同一个组织 ...
  • postgresql行列转换函数
  • 数据可视化之下发图实践
  • 曜石科技宣布获得千万级天使轮投资,全方面布局电竞产业链 ...
  • #我与Java虚拟机的故事#连载11: JVM学习之路
  • (Bean工厂的后处理器入门)学习Spring的第七天
  • (day6) 319. 灯泡开关
  • (ros//EnvironmentVariables)ros环境变量
  • (附源码)基于SSM多源异构数据关联技术构建智能校园-计算机毕设 64366
  • (个人笔记质量不佳)SQL 左连接、右连接、内连接的区别
  • (十八)devops持续集成开发——使用docker安装部署jenkins流水线服务
  • (算法)Game
  • .net Application的目录
  • .Net的C#语言取月份数值对应的MonthName值
  • ?php echo $logosrc[0];?,如何在一行中显示logo和标题?
  • @DependsOn:解析 Spring 中的依赖关系之艺术
  • @Transactional 竟也能解决分布式事务?
  • [ C++ ] STL---仿函数与priority_queue
  • [④ADRV902x]: Digital Filter Configuration(发射端)
  • [AIGC 大数据基础]hive浅谈
  • [GXYCTF2019]BabyUpload1 -- 题目分析与详解
  • [LeetCode]—Roman to Integer 罗马数字转阿拉伯数字
  • [lintcode easy]Maximum Subarray
  • [Linux]如何理解kernel、shell、bash
  • [OS-Linux] CentOS 7.x 使用密钥登录安全设置
  • [P4V]Perforce(P4V)使用教程
  • [svc]后台运行程序screen or nohup
  • [SWPU2019]Web3