java NIO实现聊天室

服务端

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

public class ChatServer {

    public ChatServer(){

    }

    public void start() throws IOException {

		//获取服务端通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        System.out.println("服务器启动");

		//设为非阻塞状态
        serverSocketChannel.configureBlocking(false);

		//设置端口号
        serverSocketChannel.bind(new InetSocketAddress(6666));

		//获取选择器
        Selector selector = Selector.open();

		//将通道注册进选择器
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

		//遍历选择器,如果大于0,说明有用户连接
        while (selector.select() > 0){
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();

            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();

				//如果是连接状态
                if (selectionKey.isAcceptable()) {
                
					//获取客户端通道,并设为非阻塞状态注册进选择器
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);

                } else if (selectionKey.isReadable()) {
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    ByteBuffer allocate = ByteBuffer.allocate(1024);

                    int len = 0;
                    while ((len = channel.read(allocate)) > 0) {
                        allocate.flip();
                        String msg = new String(allocate.array());
                        System.out.println(serverSocketChannel.getLocalAddress()+"客户端消息:"+msg);
                        allocate.clear();
                    }
                }
            }

			//必须移除,否则会一直进行已经处理的事件
            iterator.remove();
        }
    }
}

客户端


```java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class ChatClient {

    public ChatClient(){

    }

    public void start() throws IOException {
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",6666));

        socketChannel.configureBlocking(false);

        ByteBuffer allocate = ByteBuffer.allocate(1024);

        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNext()){
            String msg = scanner.next();
            allocate.put(msg.getBytes());
            allocate.flip();

            socketChannel.write(allocate);
            allocate.clear();
        }

        int len = 0;

        while ((len = socketChannel.read(allocate)) > 0){
            allocate.flip();
            System.out.println("服务端:"+new String(allocate.array()));
            allocate.clear();
        }
        socketChannel.close();
    }
}

效果
请添加图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值