NIO实现聊天场景

Server端代码

package com.example.demo;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;

public class ServerChannel {

    /**
     * 主方法
     */
    public static void main(String[] args) {
        ByteBuffer bb=ByteBuffer.allocate(1024);
        Start(bb);
    }

    public static void Start( ByteBuffer bb) {
        ServerSocketChannel ssc = null;
        Selector s = null;
        boolean tag=false;
        try {
            ssc = ServerSocketChannel.open();
            s = Selector.open();
            ssc.socket().bind(new InetSocketAddress(10086));
            ssc.configureBlocking(false);
            ssc.register(s, SelectionKey.OP_ACCEPT);
            while (true) {
                if (s.select() == 0) {
                    System.out.println("Next Loop");
                    continue;
                }
                Iterator<SelectionKey> keys = s.selectedKeys().iterator();
                while (keys.hasNext()) {
                    SelectionKey key = keys.next();
                    if (key.isAcceptable()) {
                        System.out.println(key + "______________Accept");
                        HandleAccept(key, bb);
                    }
                    if (key.isConnectable()) {
                        //System.out.println(key + "______________Connect");
                    }
                    if (key.isReadable()) {
                        //System.out.println(key + "______________Read");
                        HandleRead(key);
                    }
                    if (key.isWritable()) {
                        //System.out.println(key + "______________Write");
                        //HandleWrite(key);
                        if(!tag) {
                            inputThread(key);
                            tag=true;
                        }
                    }
                    keys.remove();
                }
                Thread.sleep(3000);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                ssc.close();
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理接受
     */
    public static void HandleAccept(SelectionKey key, ByteBuffer bb) {
        ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
        SocketChannel sc = null;
        try {
            sc = ssc.accept();
            sc.configureBlocking(false);
            sc.register(key.selector(), SelectionKey.OP_READ|SelectionKey.OP_WRITE,bb);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理读操作
     */
    public static void HandleRead(SelectionKey key) {
        SocketChannel sc = null;
        sc = (SocketChannel) key.channel();
        ByteBuffer bb=(ByteBuffer) key.attachment();
        try {
            sc.read(bb);
            bb.flip();
            System.out.println("小姐姐说:"+Charset.forName("UTF-8").newDecoder().decode(bb));
            bb.clear();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void inputThread(SelectionKey key) {
        SocketChannel sc=(SocketChannel) key.channel();
        ByteBuffer bb=(ByteBuffer) key.attachment();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("Connect with "+sc.getRemoteAddress()+" Sucessed");
                    Scanner scan = new Scanner(System.in);
                    while(true){
                        String str = scan.nextLine();
                        bb.put(str.getBytes("UTF-8"));
                        bb.flip();
                        sc.write(bb);
                        bb.clear();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        ).start();
    }

//    /**
//     * 写操作
//     */
//    public static void HandleWrite(SelectionKey key) {
//        SocketChannel sc = null;
//        sc = (SocketChannel) key.channel();
//        ByteBuffer bb = (ByteBuffer) key.attachment();
//        Scanner scan = new Scanner(System.in);
//        String str = scan.nextLine();
//        //while(!str.equals("\n")) {
//        bb.clear();
//        bb.put(str.getBytes());
//        bb.flip();
//        try {
//            sc.write(bb);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}

Client端代码

package com.example.demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;


public class ClientChannel {

    /**
     * 主函数
     * @param args
     */
    public static void main(String[] args) {
        ByteBuffer bb = ByteBuffer.allocate(1024);
        Start(bb);
    }

    /**
     * Start函数
     * @param bb
     */
    public static void Start(ByteBuffer bb) {
        SocketChannel sc = null;
        Selector s = null;
        try {
            sc = SocketChannel.open();
            s = Selector.open();
            sc.configureBlocking(false);
            sc.connect(new InetSocketAddress("localhost", 10086));
            sc.register(s, SelectionKey.OP_CONNECT, bb);
            boolean tag = false;
            while (true) {
                if (s.select() == 0) {
                    System.out.println("Next Loop");
                    continue;
                }
                Iterator<SelectionKey> keys = s.selectedKeys().iterator();
                SelectionKey key = null;
                while (keys.hasNext()) {
                    key = keys.next();
                    if (key.isConnectable()) {
                        System.out.println("Connectable");
                        sc.finishConnect();
                        key.interestOps(key.OP_WRITE | key.OP_READ);
                    }
                    if (key.isReadable()) {
                        // System.out.println("Read");
                        HandleRead(key);
                    }
                    if (key.isWritable()) {
                        //            System.out.println("Write");
                        //            System.out.println(key.interestOps());
                        // HandleWrite(key);
                        if (!tag) {
                            inputThread(key);
                            tag = true;
                        }
                    }
                    keys.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (sc != null)
                try {
                    sc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

    /**
     * 解决可写操作
     * @param key
     */
//    public static void HandleWrite(SelectionKey key) {
//        SocketChannel sc = null;
//        sc = (SocketChannel) key.channel();
//        ByteBuffer bb = ByteBuffer.allocate(1024);
//        Scanner scan = new Scanner(System.in);
//        System.out.println("Please Input Some Info:");
//        String str = scan.nextLine();
//        bb.clear();
//        bb.put(str.getBytes());
//        bb.flip();
//        try {
//            sc.write(bb);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 可读操作
     */
    public static void HandleRead(SelectionKey key) {
        SocketChannel sc = (SocketChannel) key.channel();
        ByteBuffer bb = (ByteBuffer) key.attachment();
        try {
            sc.read(bb);
            bb.flip();
            while (bb.hasRemaining())
                System.out.println(Charset.forName("UTF-8").newDecoder().decode(bb));
            bb.clear();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 捕捉键盘输入
     * @param key
     */
    public static void inputThread(SelectionKey key) {
        SocketChannel sc = (SocketChannel) key.channel();
        ByteBuffer bb = (ByteBuffer) key.attachment();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("Connect with " + sc.getRemoteAddress() + " Sucessed");
                    Scanner scan = new Scanner(System.in);
                    while (true) {
                        String str = scan.nextLine();
                        bb.put(str.getBytes("UTF-8"));
                        bb.flip();
                        sc.write(bb);
                        bb.clear();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值