nio

package com.chigo.it.bio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
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;

/**
 * @description:
 * @project: chigo
 * @version: 1.0
 */
public class Server1 {
    public static void main(String[] args) {
        new Server1().listen();
    }
    private ServerSocketChannel serverSocketChannel;
    private Selector selector;
    private boolean aBoolean;

    public Server1() {
        try {
            this.selector = Selector.open();
            this.serverSocketChannel = ServerSocketChannel.open();
            this.serverSocketChannel.configureBlocking(false);
            this.serverSocketChannel.bind(new InetSocketAddress(9999));
            this.serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen(){
        try {
            while (true){
                int count = selector.select();
                if (count>0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        if (selectionKey.isAcceptable()) {
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector,SelectionKey.OP_READ);
                            System.out.println(socketChannel.getRemoteAddress() + " 上线了");
                        }
                        if (selectionKey.isReadable()) {
                            Channel channel = selectionKey.channel();
                            readMessage(selectionKey);
                        }
                        iterator.remove();
                    }
                }else {
                    System.out.println("等待连接");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void readMessage(SelectionKey selectionKey) {
        SocketChannel socketChannel = null;
        try {
            socketChannel = (SocketChannel) selectionKey.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = 0;
            try {
                count = socketChannel.read(buffer);
            } catch (IOException e) {
                System.out.println(socketChannel.getRemoteAddress().toString() + " 离线了");
                socketChannel.close();
                selectionKey.cancel();
            }
            if (count>0) {
                String message = new String(buffer.array());
                System.out.println("收到客户端的信息   " + message);
                redisMessage(message,socketChannel);
            }
        }catch (IOException e) {
            e.printStackTrace();
            try {
                socketChannel.close();
                selectionKey.cancel();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    public void redisMessage(String message,SocketChannel socketChannel) throws IOException {
        System.out.println("服务器转发信息中");
        for (SelectionKey key : selector.keys()) {
            Channel channel = key.channel();
            if (channel instanceof SocketChannel && channel !=socketChannel){
                SocketChannel socketChannel1 = (SocketChannel) channel;
                socketChannel1.write(ByteBuffer.wrap(message.getBytes()));
            }
        }
    }
}

package com.chigo.it.bio;

import com.sun.org.apache.bcel.internal.generic.NEW;
import jdk.internal.org.objectweb.asm.tree.TryCatchBlockNode;

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.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @description:
 * @version: 1.0
 */
public class client {
    public static void main(String[] args) throws IOException {
        client client = new client();
        new Thread(()->{
            while (true){
                client.readmessage();
                try {
                    Thread.currentThread().sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String message = scanner.nextLine();
            client.sentMessage(message);
        }
    }
    private SocketChannel socketChannel;
    private String host ="127.0.0.1";
    private int porit = 9999;
    private Selector selector;
    private String username;
    
    public client() throws IOException {
        this.socketChannel = SocketChannel.open(new InetSocketAddress(host,porit));
        this.selector = Selector.open();
        this.username = socketChannel.getLocalAddress().toString().substring(1);
        this.socketChannel.configureBlocking(false);
        this.socketChannel.register(selector, SelectionKey.OP_READ);
        System.out.println("客户端准备就绪");
    }
    
    public void sentMessage(String message){
        message = username+" 说: "+message;
        try {
            socketChannel.write(ByteBuffer.wrap(message.getBytes()));
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            
        }
    }
    
    public void readmessage(){
        try {
            int count = selector.select();
            if (count>0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isReadable()) {
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        int read = channel.read(buffer);
                        System.out.println("收到信息"+ new String(buffer.array()).trim());
                    }
                }
                iterator.remove();
            }else {
                //System.out.println("mei you ke you tong dao");
            }
        }catch (IOException e){
            try {
                socketChannel.close();
                selector.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }finally {
            
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值