70 lines
2.1 KiB
Java
70 lines
2.1 KiB
Java
package com.thinker.common.nio;
|
|
|
|
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;
|
|
|
|
public class NioClient{
|
|
//通道管理器
|
|
private Selector selector;
|
|
public NioClient init(String ip, int port) throws IOException{
|
|
//获取socket通道
|
|
SocketChannel channel = SocketChannel.open();
|
|
|
|
channel.configureBlocking(false);
|
|
//获取通道管理器
|
|
selector = Selector.open();
|
|
|
|
channel.connect(new InetSocketAddress(ip, port));
|
|
|
|
channel.register(selector, SelectionKey.OP_CONNECT);
|
|
return this;
|
|
}
|
|
|
|
public void listen() throws IOException{
|
|
System.out.println("client start");
|
|
//轮询访问selector
|
|
while(true){
|
|
//选择注册过io的事件(第一次为SelectionKey.OP_CONNECT)
|
|
selector.select();
|
|
Iterator<SelectionKey> ite = selector.selectedKeys().iterator();
|
|
while(ite.hasNext()){
|
|
SelectionKey key = ite.next();
|
|
ite.remove();
|
|
if(key.isConnectable()){
|
|
SocketChannel channel = (SocketChannel)key.channel();
|
|
if(channel.isConnectionPending()){
|
|
channel.finishConnect();
|
|
}
|
|
channel.configureBlocking(false);
|
|
//send message to service
|
|
channel.write(ByteBuffer.wrap(new String("send message to service").getBytes()));
|
|
channel.register(selector, SelectionKey.OP_READ);
|
|
System.out.println("client connect success");
|
|
}else if(key.isReadable()){//read message
|
|
SocketChannel channel = (SocketChannel) key.channel();
|
|
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
|
channel.read(buffer);
|
|
byte[] data = buffer.array();
|
|
String message = new String(data);
|
|
System.out.println("receive message size:"+buffer.position()+"\tmessage:"+message);
|
|
try{
|
|
Thread.sleep(1000);
|
|
}catch(InterruptedException e){
|
|
e.printStackTrace();
|
|
break;
|
|
}
|
|
channel.write(ByteBuffer.wrap(new String("hello ,service").getBytes()));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
public static void main(String[] args) throws IOException{
|
|
new NioClient().init("127.0.0.1",1994).listen();
|
|
}
|
|
}
|