zoukankan      html  css  js  c++  java
  • 【nio网络编程】发送消息

    写的比较简单,没有异步输入消息,参考韩顺平老师的讲解

    server.java

    package com.company;
    
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.*;
    import java.nio.charset.StandardCharsets;
    import java.util.Iterator;
    import java.util.Set;
    
    public class Server {
        static Selector selector ;
        static ServerSocketChannel serverSocketChannel;
    
        public static void main(String[] args) throws Exception {
            selector = Selector.open();
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress(8080));
    
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    
            while (true) {
                int count = selector.select(1000);
                if (count > 0) {
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
    
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        if (key.isAcceptable()) {
                            SocketChannel accept = serverSocketChannel.accept();
                            accept.configureBlocking(false);
                            accept.register(selector, SelectionKey.OP_READ);
                            System.out.println(accept.getRemoteAddress() + " 上线了");
                        }
                        if (key.isReadable()) {
                            // todo
                            readData(key);
                        }
                        iterator.remove();
                    }
    
    
                } else {
    //                System.out.println("等待ing");
                }
    
            }
    
    
        }
    
        private static void readData(SelectionKey key) {
            SocketChannel channel = null;
            try {
                channel = (SocketChannel)key.channel();
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                int read = channel.read(buffer);
                if (read>0) {
                    String string = new String(buffer.array(), 0, buffer.position(), StandardCharsets.UTF_8);
                    System.out.println("客户端发送"+string);
                    sendInfoToOther(string, channel);
                }
            } catch (IOException e) {
                try {
                    System.out.println(channel.getRemoteAddress() + "离线了");
                    key.cancel();
                    channel.close();
                    e.printStackTrace();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
    
            }
    
    
        }
    
        private static void sendInfoToOther(String string, SocketChannel self) throws IOException {
            for (SelectionKey key : selector.keys()) {
                Channel channel = key.channel();
                if(channel instanceof SocketChannel && channel != self ){
                    SocketChannel target = (SocketChannel) channel;
                    ByteBuffer buffer = ByteBuffer.wrap(string.getBytes(StandardCharsets.UTF_8));
                    target.write(buffer);
                }
    
            }
        }
    }

    Client.java

    package com.company;
    
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.nio.charset.StandardCharsets;
    import java.util.Iterator;
    import java.util.Set;
    
    public class Client {
        public static void main(String[] args) throws IOException {
            Selector selector = Selector.open();
            SocketChannel sc = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8080));
            sc.configureBlocking(false);
            sc.register(selector, SelectionKey.OP_READ);
    
            String username = sc.getLocalAddress().toString().substring(1);
            System.out.println("username" + username);
            sc.write(ByteBuffer.wrap((username + "说 你好").getBytes(StandardCharsets.UTF_8)));
    
            while (true) {
                int count = selector.select(1000);
                if (count > 0) {
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey next = iterator.next();
                        if (next.isReadable()) {
                            SocketChannel channel = (SocketChannel) next.channel();
                            ByteBuffer buff = ByteBuffer.allocate(1024);
                            channel.read(buff);
                            String s = new String(buff.array(), 0, buff.position(), StandardCharsets.UTF_8);
                            System.out.println(s);
                        } else {
                            System.out.println("没有可用的通道");
                        }
                        iterator.remove();
                    }
                }
            }
    
    
        }
    
    
    }

     

    转载注明出处 一支小白 - 博客园http://www.cnblogs.com/startnow/ - 联系:tungshuaishuai@sina.com
  • 相关阅读:
    二叉树 Java 实现 前序遍历 中序遍历 后序遍历 层级遍历 获取叶节点 宽度 ,高度,队列实现二叉树遍历 求二叉树的最大距离
    Java:JUnit4使用详解
    Java 常用数据结构对象的实现原理 集合类 List Set Map 哪些线程安全 (美团面试题目)
    JAVA里的布尔运算符-甲骨文面试题
    try catch finally 用法
    Java的JDBC事务详解
    Java开发中JDBC连接数据库代码和步骤
    WebUploader文件图片上传插件的使用
    webuploader解决不能重复上传问题及一些常见问题处理
    HTML5 input file控件使用accept过滤限制的文件类型以及在谷歌下打开很慢的问题
  • 原文地址:https://www.cnblogs.com/startnow/p/15690709.html
Copyright © 2011-2022 走看看