欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java NIO实现简单聊天程序

程序员文章站 2022-07-06 11:15:08
本文实例为大家分享了java nio实现简单聊天程序的具体代码,供大家参考,具体内容如下服务端功能:1、接受客户端连接2、发送消息3、读取客户端消息server.javapublic class se...

本文实例为大家分享了java nio实现简单聊天程序的具体代码,供大家参考,具体内容如下

服务端

功能:

1、接受客户端连接
2、发送消息
3、读取客户端消息

server.java

public class server {

    private selector selector;
    private bytebuffer writebuffer = bytebuffer.allocate(1024);
    private bytebuffer readbuffer = bytebuffer.allocate(1024);
    msg msg = new msg();
    msgsender msgsender = new msgsender(msg);
    public static void main(string[] args) {
        server server = new server();
        new thread(server.msgsender).start();
        server.start();

    }

    //初始化服务端
    public server() {
        try {
            this.selector = selector.open();
            serversocketchannel ssc = serversocketchannel.open();
            ssc.configureblocking(false);
            ssc.bind(new inetsocketaddress(8899));
            ssc.register(this.selector, selectionkey.op_accept);
            system.out.println("服务端初始化完毕。。。。");
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }

    //启动服务端等待selector事件
    public void start() {
        while (true) {
            try {
                int num = this.selector.select();
                if (num > 0) {
                    iterator<selectionkey> it = this.selector.selectedkeys().iterator();
                    while (it.hasnext()) {
                        selectionkey key = it.next();
                        it.remove();
                        if (key.isvalid()) {
                            if (key.isacceptable()) {
                                this.accept(key);
                            }
                            if (key.isreadable()) {
                                this.read(key);
                            }
                            if (key.iswritable()) {
                                this.write(key);
                            }
                        }
                    }
                }
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }
    }

    //发送消息
    private void write(selectionkey key) {
        socketchannel sc = (socketchannel) key.channel();
        try {
            sc.configureblocking(false);
        } catch (ioexception e) {
            e.printstacktrace();
        }
  //判断是否有消息需要发送
        if(msg!=null && msg.getflag()){
            system.out.println(msg);
            try {
                msg.setflag(false);
                writebuffer.clear();
                writebuffer.put(msg.getcontent().getbytes());
                writebuffer.flip();
                sc.write(writebuffer);
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }


    }

    //读取客户端消息
    private void read(selectionkey key) {
        socketchannel sc = (socketchannel) key.channel();
        try {
            sc.configureblocking(false);
            readbuffer.clear();
            int read = sc.read(readbuffer);
            if (read == -1) {
                sc.close();
                key.cancel();
            }
            readbuffer.flip();
            system.out.println(new string(readbuffer.array()));
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }

    //接受客户端连接
    private void accept(selectionkey key) {
        serversocketchannel ssc = (serversocketchannel) key.channel();
        try {
            socketchannel sc = ssc.accept();
            system.out.println(string.format("a new client join!!!host:%s;port:%d", sc.socket().getlocaladdress(), sc.socket().getport()));
            sc.configureblocking(false);
            sc.register(this.selector, selectionkey.op_read | selectionkey.op_write);
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }

}

msg.java

class msg {
    private boolean flag=false;
    private string content;

    public boolean getflag() {
        return flag;
    }

    public void setflag(boolean flag) {
        this.flag = flag;
    }

    public string getcontent() {
        return content;
    }

    public void setcontent(string content) {
        this.content = content;
    }

    @override
    public string tostring() {
        return "msg{" +
                "flag=" + flag +
                ", content='" + content + '\'' +
                '}';
    }
}

msgsender.java

class msgsender implements runnable{
    private msg msg;

    public msgsender(msg msg) {
        this.msg = msg;
    }

    @override
    public void run() {
        while (true) {
            system.out.println("input:\n");
            scanner scanner = new scanner(system.in);
            this.msg.setcontent(scanner.next());
            this.msg.setflag(true);
        }
    }
}

客户端

采用的时bio,简单的使用线程实现消息的读写

功能:

1、连接服务端
2、读取消息
3、发送消息

public class client {
    private socketchannel sc;
    bytebuffer writebuffer = bytebuffer.allocate(1024);
    bytebuffer readbuffer = bytebuffer.allocate(1024);

    public static void main(string[] args) {
        new client();
    }
    public client() {
        try {
            sc = socketchannel.open();
            //连接服务端
            sc.connect(new inetsocketaddress(8899));
            //发送消息
            this.write(sc);
            //读取消息
            this.read(sc);
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }

    private void read(socketchannel sc) {
        new thread(new runnable() {
            @override
            public void run() {
                while (true) {
                    try {
                        readbuffer.clear();
                        int read = sc.read(readbuffer);
                        readbuffer.flip();
                        system.out.println(new string(readbuffer.array()));
                    } catch (ioexception e) {
                        e.printstacktrace();
                    }
                }
            }
        }).start();
    }

    private void write(socketchannel sc) {
        new thread(new runnable() {
            @override
            public void run() {
                while (true) {
                    scanner scanner = new scanner(system.in);
                    string next = scanner.next();
                    writebuffer.clear();
                    writebuffer.put(next.getbytes());
                    writebuffer.flip();
                    try {
                        sc.write(writebuffer);
                    } catch (ioexception e) {
                        e.printstacktrace();
                    }
                }
            }
        }).start();
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

相关标签: java NIO 聊天