java nio selector.select()_Java NIO (四) 选择器(Selector)

48304ba5e6f9fe08f3fa1abda7d326ab.png

import java.io.IOException;

import java.net.InetSocketAddress;

import java.net.ServerSocket;

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.Set;

/**

* Created by 58 on 2016/11/28.

*/

public class SelectorServer {

public static void main(String args[]){

startServer();

}

public static ByteBuffer sendBuffer = ByteBuffer.allocate(1024);

public static ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);

public static void startServer(){

//用两个channel监听两个端口

int listenPort = 8888;

int listenPort1 = 8889;

sendBuffer.put("message from server".getBytes());

try {

//创建serverchannel,绑定对应的端口

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

ServerSocket serverSocket = serverSocketChannel.socket();

InetSocketAddress inetSocketAddress = new InetSocketAddress(listenPort);

serverSocket.bind(inetSocketAddress);

//创建第二个channel

ServerSocketChannel serverSocketChannel1 = ServerSocketChannel.open();

ServerSocket serverSocket1 = serverSocketChannel1.socket();

InetSocketAddress inetSocketAddress1 = new InetSocketAddress(listenPort1);

serverSocket1.bind(inetSocketAddress1);

//创建selector对象

Selector selector = Selector.open();

//设置channel注册到selector中

serverSocketChannel.configureBlocking(false);

serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

//第二个channel

serverSocketChannel1.configureBlocking(false);

serverSocketChannel1.register(selector, SelectionKey.OP_ACCEPT);

System.out.println("start to listen port: " + listenPort);

System.out.println("start to listen port: " + listenPort1);

//监听端口

while(true){

int readyChannels = selector.select();

if(readyChannels == 0)

continue;

Set selectedKeys = selector.selectedKeys();

Iterator iterator = selectedKeys.iterator();

while(iterator.hasNext()){

SelectionKey selectionKey = iterator.next();

dealSelectionKey(selector, selectionKey);

iterator.remove();

}//while

}//while

} catch (IOException e) {

e.printStackTrace();

}

}

public static void dealSelectionKey(Selector selector, SelectionKey selectionKey){

try{

//准备好接收新的连接

if(selectionKey.isAcceptable()){

ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();

SocketChannel clientSocketChannel = serverSocketChannel.accept();

clientSocketChannel.configureBlocking(false);

clientSocketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);

System.out.println("channel is ready acceptable");

}

else if(selectionKey.isConnectable()){

selectionKey.channel().register(selector, SelectionKey.OP_READ);

System.out.println("channel is connectable.");

}

else if(selectionKey.isReadable()){

//读去客户端内容

SocketChannel clientSocketChannel = (SocketChannel) selectionKey.channel();

receiveBuffer.clear();

clientSocketChannel.read(receiveBuffer);

selectionKey.interestOps(SelectionKey.OP_WRITE);

System.out.println("message from client is: " + new String(receiveBuffer.array()));

System.out.println("Thread id : " + Thread.currentThread().getId());

}

else if(selectionKey.isWritable()){

//向客户端写数据

SocketChannel clientSocketChannel = (SocketChannel) selectionKey.channel();

sendBuffer.flip();

System.out.println("sendBuffer = " + new String(sendBuffer.array()));

clientSocketChannel.write(sendBuffer);

selectionKey.interestOps(SelectionKey.OP_READ);

System.out.println("channle is writable.");

}//else if

}catch (Exception e){

}

}

}

client:

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.SocketChannel;

import java.util.Iterator;

import java.util.Set;

/**

* Created by 58 on 2016/11/28.

*/

public class SelectorClient {

public static void main(String args[]){

work();

}

public static void work(){

int serverPort = 8888;

ByteBuffer sendBuffer = ByteBuffer.wrap("client message".getBytes());

ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);

try {

//创建通道,设置通道注册到selector中

SocketChannel socketChannel = SocketChannel.open();

Selector selector = Selector.open();

socketChannel.configureBlocking(false);

socketChannel.register(selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ | SelectionKey.OP_CONNECT);

socketChannel.connect(new InetSocketAddress("localhost", serverPort));

int executeTimes = 2;

//while

while(executeTimes > 0){

executeTimes--;

int reayChannelNum = selector.select();

if(reayChannelNum == 0){

continue;

}

Set setOfSelectionKey = selector.selectedKeys();

Iterator iterator = setOfSelectionKey.iterator();

while(iterator.hasNext()){

SelectionKey selectionKey = iterator.next();

SocketChannel socketChannel1 = (SocketChannel) selectionKey.channel();

iterator.remove();

if(selectionKey.isConnectable()){

if(socketChannel1.isConnectionPending()){

socketChannel1.finishConnect();

System.out.println("connection complete.");

socketChannel1.write(sendBuffer);

}

}//if isConnectable

else if(selectionKey.isReadable()){

receiveBuffer.clear();

socketChannel1.read(receiveBuffer);

receiveBuffer.flip();

System.out.println("message from server: " + new String(receiveBuffer.array()));

}//else if readable

else if(selectionKey.isWritable()){

sendBuffer.flip();

socketChannel1.write(sendBuffer);

}

}

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

48304ba5e6f9fe08f3fa1abda7d326ab.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值