SocketChannel服务器端
package mailclass;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
/**
*
* @author AAries zyz!
*/
public class Client extends Thread {
private Selector selector;
public Client(Selector selector) {
this.selector = selector;
Thread thread = new Thread(this);
thread.start();;
}
@Override
public void run() {
try {
while (selector.select() > 0) {
// 遍历每个有可用IO操作Channel对应的SelectionKey
Iterator it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey sk = (SelectionKey) it.next();
it.remove();
// 如果该SelectionKey对应的Channel中有可读的数据
if (sk.isReadable()) {
// 使用NIO读取Channel中的数据
SocketChannel socketChannel = (SocketChannel) sk.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
socketChannel.read(buffer);
buffer.flip();
// 将字节转化为为UTF-16的字符串
String receivedString = Charset.forName("UTF-16").newDecoder().decode(buffer).toString();
// 控制台打印出来
System.out.println("接收到来自服务器" + socketChannel.socket().getRemoteSocketAddress() + "的信息:" + receivedString);
// 为下一次读取作准备
// sk.interestOps(SelectionKey.OP_READ);//将键设为可读
}
if (sk.isWritable()) {
SocketChannel socketChannel = (SocketChannel) sk.channel();
ByteBuffer writeBuffer = ByteBuffer.wrap("我的程序员之道".getBytes("UTF-16"));
socketChannel.write(writeBuffer);
}
// 删除正在处理的SelectionKey
selector.selectedKeys().remove(sk);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
调用类的写法
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mailclass;
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;
/**
*
* @author AAries zyz!
*/
class ClientTest {
public static void main(String[] args) throws IOException {
SocketChannel sc = SocketChannel.open(new InetSocketAddress("172.16.22.11", 5200));
//打开一耳光SocketChannel并连接
sc.configureBlocking(false);
Selector selector = Selector.open();
sc.register(selector, SelectionKey.OP_READ);
//注册一个selector此时为空
Client client = new Client(selector);
//打开一个线程,如遇到可读的包则读取,如遇到可写的包,则写!
ByteBuffer writeBuffer=ByteBuffer.wrap("我的程序员之道".getBytes("UTF-16"));
sc.write(writeBuffer);
}
}