NIO服务端的读写

xiaoxiao2025-08-21  51

import java.io.IOException; 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; import java.util.Scanner; import java.util.Set;

/**   * 类说明  :NIO服务端的读写 * @author   郭莹棋 * @date 2018年10月19日 */

public class NioServerGy { public static void main(String[] args) throws IOException {     int port = 5555;     //获取ServerSocket信道实例     ServerSocketChannel sc = ServerSocketChannel.open();     //绑定信道端口     sc.bind(new InetSocketAddress(port));     //设置为非阻塞     sc.configureBlocking(false);     //获取Selector实例     Selector s = Selector.open();     //当前信道接受网络请求     sc.register(s, SelectionKey.OP_ACCEPT);     //设置标识     int num = 0;     //开辟一个50字节的空间出来     ByteBuffer buffer = ByteBuffer.allocate(50);     //获取所有信道数量     while((num = s.select()) >= 0) {         Set<SelectionKey> keys = s.selectedKeys();         Iterator<SelectionKey> iterator = keys.iterator();         while(iterator.hasNext()) {             SelectionKey key = iterator.next();             if(!key.isValid()) {                 key.cancel();                 continue;             }         if(key.isAcceptable()) {             System.out.println("当前信道为接收请求");             //当前信道接收请求             ServerSocketChannel channel = (ServerSocketChannel)key.channel();             //获取相连的客户端请求             SocketChannel client = channel.accept();             //设置接收数据信道为非阻塞             client.configureBlocking(false);             //将该信道注册到Selector上             channel.register(s, SelectionKey.OP_READ);             key.cancel();             continue;         }         if(key.isReadable()) {             SocketChannel channel = (SocketChannel)key.channel();             int read = channel.read(buffer);             String string = new String(buffer.array(),0,buffer.remaining());             System.out.println("[client]"+string);             buffer.clear();             String recvMsg = "[server]"+string;             buffer.put(recvMsg.getBytes());             //buffer.flip();             //channel.write(buffer);             channel.register(s,SelectionKey.OP_WRITE );             buffer.clear();             key.cancel();             continue;             }         if(key.isWritable()) {             SocketChannel channel = (SocketChannel)key.channel();             Scanner cc = new Scanner(System.in);             String ss = cc.nextLine();             channel.write(ByteBuffer.wrap(ss.getBytes()));         }         }     } } }

转载请注明原文地址: https://www.6miu.com/read-5035077.html

最新回复(0)