package cn.zvc.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
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.Set;
public class NIOServer {
private int blockSize = 4096;
private ByteBuffer sendBuffer = ByteBuffer.allocate(blockSize);
private ByteBuffer receiveBuffer = ByteBuffer.allocate(blockSize);
private Selector selector;
private int flag = 1;
public NIOServer(int port) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//设置是否阻塞
serverSocketChannel.configureBlocking(false);
ServerSocket serverSocket = serverSocketChannel.socket();
serverSocket.bind(new InetSocketAddress(port));
selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("server start:" + port);
}
public void linsten() throws IOException{
while(true) {
selector.select();
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> it = selectionKeys.iterator();
while(it.hasNext()) {
SelectionKey sk = it.next();
it.remove();
//业务逻辑
handleKey(sk);
}
}
}
public void handleKey(SelectionKey sk) throws IOException{
ServerSocketChannel server = null;
SocketChannel client = null;
String reviceText;
String sendText;
int count = 0;
if(sk.isAcceptable()){
server = (ServerSocketChannel) sk.channel();
client = server.accept();
client.configureBlocking(false);
client.register(selector, sk.OP_READ);
} else if(sk.isReadable()) {
client = (SocketChannel) sk.channel();
count = client.read(receiveBuffer);
if(count>0){
reviceText = new String(receiveBuffer.array(),0,count);
System.out.println("服务端接受到客户端的信息:"+ reviceText);
client.register(selector, SelectionKey.OP_WRITE);
}
} else if(sk.isWritable()){
receiveBuffer.clear();
client = (SocketChannel) sk.channel();
sendText = "msg send to client:"+ flag;
sendBuffer.put(sendText.getBytes());
sendBuffer.flip();
client.write(sendBuffer);
System.out.println("服务端发送给客户端:"+ sendText);
}
}
public static void main(String[] args) {
}
}
java nio
点赞
收藏