使用NIO可以使JAVA具有非阻塞式网络编程的能力,下面是一个小例子
package test;
import java.net.InetSocketAddress;
import java.net.Socket;
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;
public class NIOServer {
private static int connections;
private static Selector selector;
public NIOServer() throws Exception {
selector = Selector.open();
ServerSocketChannel ssChannel = ServerSocketChannel.open();
ssChannel.socket().bind(new InetSocketAddress(3721));
ssChannel.configureBlocking(false);
ssChannel.register(selector, SelectionKey.OP_ACCEPT);
for(;;){
selector.select();//等待接收事件
for(Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
keyIterator.hasNext();){
SelectionKey key = keyIterator.next();
keyIterator.remove();
handleSelectionKey(key);
System.out.println("事件处理完一次...");
}
}
}
//处理消息
private static void handleSelectionKey(SelectionKey key) throws Exception {
if(key.isAcceptable()){
connections++;
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
Socket socket = sc.socket();
sc.register(selector, SelectionKey.OP_READ);
System.out.println("第"+connections+" 个客户端【"+socket.getRemoteSocketAddress()+"】");
}else if(key.isReadable()){
ByteBuffer byteBuffer = ByteBuffer.allocate(200);
// byteBuffer.put("I'm from server".getBytes());
SocketChannel sc = (SocketChannel) key.channel();
sc.read(byteBuffer);
byteBuffer.put((byte) '\n');
byteBuffer.flip();
System.out.println(new String(byteBuffer.array()).toString());
sc.write(byteBuffer);
System.out.println("向客户端发送完毕...");
}else if(key.isWritable()){
System.out.println("当前key类型:writable...");
}else if(key.isConnectable()){
System.out.println("当前key类型:connectable...");
}else{
System.out.println("其他类型...");
}
}
public static void main(String[] args) throws Exception {
new NIOServer();
}
}
客户端:
package test;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
public class NIOClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost",3721);
System.out.println("连接完毕!");
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
DataInputStream dis = new DataInputStream(s.getInputStream());
dos.writeUTF("abcde......");
System.out.println(dis.readLine());
dos.close();
s.close();
}
}