NIO服务器和客户端通讯简单例子

NIO服务器和客户端通讯简单例子

废话不多说直接上代码。
首先是服务端代码:

package nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NioServer {

    public Selector selector;

    //初始化服务器
    public void initServer(int port) throws Exception{
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //非阻塞
        serverSocketChannel.configureBlocking(false);
        //绑定端口
        serverSocketChannel.bind(new InetSocketAddress(port));
        //获取一个通道管理器
        selector = Selector.open();
        //1.绑定通道管理器;
        //2.当事件到达时,selector.seletor()会返回否则会一直阻塞,此时注册的是OP_ACCEPT事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }

    //监听事件并处理
    public void listen() throws Exception{
        while(true){
            //当事件到达时,selector.seletor()会返回否则会一直阻塞
            selector.select();
            System.out.println("接收到了");
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while(iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                iterator.remove();
                handle(selectionKey);
            }
        }
    }

    //处理
    public void handle(SelectionKey selectionKey) throws Exception{
        if(selectionKey.isAcceptable()){
            handleaccept(selectionKey);
        }else if(selectionKey.isReadable()){
            handleread(selectionKey);
        }
    }

    //如果接收到客户端请求则将该channel改成监听on_read状态
    public void handleaccept(SelectionKey selectionKey) throws Exception{
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
        SocketChannel socketChannel = serverSocketChannel.accept();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
    }

    public void handleread(SelectionKey selectionKey) throws Exception{
        //取消读事件的监控
        selectionKey.cancel();
        SocketChannel readChannel = (SocketChannel) selectionKey.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.clear();
        readChannel.read(buffer);
        System.out.println("服务器端接收到的数据:"+ new String(buffer.array()).trim());
    }

    public static void main(String[] args) throws Exception {
        NioServer server = new NioServer();
        server.initServer(8000);
        server.listen();
    }
}

客户端代码:

package nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NioClient {
    public static void main(String[] args) throws Exception {
        SocketChannel socketChannel = SocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(8000);
        socketChannel.connect(inetSocketAddress);
        String msg="我是客户端"+Thread.currentThread().getId();
        ByteBuffer buffer=ByteBuffer.allocate(1024);
        buffer.put(msg.getBytes());
        buffer.flip();
        socketChannel.write(buffer);
        socketChannel.shutdownOutput();
    }
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值