客户端代码:
package test;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class Client {
public static void main(String[] args) {
try(SocketChannel socketChannel = SocketChannel.open()){
socketChannel.connect(new InetSocketAddress("127.0.0.1",8800));
ByteBuffer writeBuff = ByteBuffer.allocate(1024);
ByteBuffer readBuff = ByteBuffer.allocate(1024);
writeBuff.put("Hello server".getBytes());
writeBuff.flip();
while (true){
writeBuff.rewind();
socketChannel.write(writeBuff);
readBuff.clear();
socketChannel.read(readBuff);
System.out.println("Client receive:" + new String(readBuff.array()));
}
}catch (Exception ex){
ex.printStackTrace();
}
}
}
服务器端代码
package test;
import java.net.InetSocketAddress;
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;
public class Server {
public static void main(String[] args) {
try (Selector selector = Selector.open()) {
try (ServerSocketChannel ssc = ServerSocketChannel.open()) {
ssc.socket().bind(new InetSocketAddress("127.0.0.1", 8800));
ssc.configureBlocking(false);
ssc.register(selector, SelectionKey.OP_ACCEPT);
ByteBuffer readBuff = ByteBuffer.allocate(1024);
ByteBuffer writeBuff = ByteBuffer.allocate(1024);
writeBuff.put("Hello client".getBytes());
writeBuff.flip();
while (true) {
int readyNum = selector.select();
if (readyNum == 0) {
continue;
}
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isAcceptable()) {
SocketChannel socketChannel = ssc.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
try(SocketChannel socketChannel = (SocketChannel) key.channel()){
readBuff.clear();
socketChannel.read(readBuff);
readBuff.flip();
System.out.println("Server receive:" + new String(readBuff.array()));
key.interestOps(SelectionKey.OP_WRITE);
}
} else if (key.isWritable()) {
try(SocketChannel socketChannel = (SocketChannel) key.channel()){
writeBuff.rewind();
socketChannel.write(writeBuff);
key.interestOps(SelectionKey.OP_READ);
}
}
iterator.remove();
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}