SocketChannel Demo

ByteBuffer封装

byteBuffer = ByteBuffer.allocate(16);// 分配这个大小的缓冲区
byteBuffer = ByteBuffer.wrap(new byte[16]);// 根据数组大小封装

这两个是一样的

ByteBuffer 用法

参考别人写的
java.nio.ByteBuffer用法小结

Demo

Server

public class Server {
	static int capacity = 1024*10;
	public void open() throws IOException {
		Selector selector = Selector.open();
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open().bind(new InetSocketAddress(9999));
		serverSocketChannel.configureBlocking(false);// 非阻塞
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
		while(true) {
			selector.select(1000);// 等待1000ms
			Set<SelectionKey> selectedKeys = selector.selectedKeys();
			Iterator<SelectionKey> iterator = selectedKeys.iterator();
			SelectionKey key = null;
			while(iterator.hasNext()) {
				key = iterator.next();
				handle(key);
				iterator.remove();// 必须要有,不然下次轮询又会出现
			}
		}
	}
	public void handle(SelectionKey key) {
		if(key.isAcceptable()) {
			doAccept(key);
		} else if(key.isReadable()) {
			doRead(key);
		}
	}
	public void doAccept(SelectionKey key) {
		try {
			ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
	        System.out.println("ServerSocketChannel正在循环监听");
	        SocketChannel clientChannel = serverChannel.accept();
	        clientChannel.configureBlocking(false);
	        clientChannel.register(key.selector(),SelectionKey.OP_READ);
		}catch(IOException e) {e.printStackTrace();}
	}
	public void doRead(SelectionKey key) {
		try {
			SocketChannel clientChannel = (SocketChannel) key.channel();
	        ByteBuffer byteBuffer = ByteBuffer.allocate(capacity);
	        int bytesRead = clientChannel.read(byteBuffer);
	        if (bytesRead == -1){
	            clientChannel.close();
	        }
	        else if(bytesRead > 0){
	            byteBuffer.flip();
	            byte[] data = new byte[byteBuffer.remaining()];
	            byteBuffer.get(data);
	            String info = new String(data);
	            System.out.println("从客户端发送过来的消息是:"+info);
	        }
	        
		}catch(IOException e) {e.printStackTrace();}
	}
	public static void main(String args[]){
		try {
			new Server().open();
		}catch(IOException e) {e.printStackTrace();}
	}
}

Client

public class Client {
	static int capacity = 1024*10;
	public void open() throws IOException {
		Selector selector = Selector.open();
		SocketChannel socketChannel = SocketChannel.open();
		socketChannel.configureBlocking(false);// 非阻塞
		socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));
		socketChannel.register(selector, SelectionKey.OP_CONNECT);
		while(true) {
			selector.select();
			Set<SelectionKey> selectedKeys = selector.selectedKeys();
			Iterator<SelectionKey> iterator = selectedKeys.iterator();
			SelectionKey key = null;
			while(iterator.hasNext()) {
				key = iterator.next();
				handle(key);
				iterator.remove();// 必须要有,不然下次轮询又会出现该SelectionKey对象
			}
		}	
	}
	public void handle(SelectionKey key) {
		if(key.isConnectable()) {
			doConnect(key);
		} else if(key.isWritable()) {
			doWrite(key);
		}
	}
	public void doConnect(SelectionKey key) {
		try {
			SocketChannel clientChannel = (SocketChannel) key.channel();
	        if (clientChannel.isConnectionPending()){
	            clientChannel.finishConnect();
	        }
	        clientChannel.configureBlocking(false);
	        String info = "服务端你好!!";
	        ByteBuffer byteBuffer = ByteBuffer.allocate(capacity);
	        byteBuffer.put(info.getBytes());
	        byteBuffer.flip();
	        clientChannel.write(byteBuffer);
	        clientChannel.register(key.selector(),SelectionKey.OP_WRITE);
		}catch(IOException e) {e.printStackTrace();}
	}
	public void doWrite(SelectionKey key) {
		try {
			SocketChannel clientChannel = (SocketChannel) key.channel();
			byte[] b = "保存消息".getBytes();
			ByteBuffer byteBuffer = ByteBuffer.wrap(b);
			byteBuffer.put(b);
			byteBuffer.flip();
			clientChannel.write(byteBuffer);
			clientChannel.close();
		}catch(IOException e) {e.printStackTrace();}
	}
	public static void main(String args[]){
		try {
			new Client().open();
		}catch(IOException e) {e.printStackTrace();}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值