客户端代码
String serverIp = “127.0.0.1”;
int serverPort = 8080;
AsynchronousSocketChannel client = Asynchronous socket Channel.open();
client.connect(new InetSocketAddress(serverIp, serverPort), “from client”,
new CompletionHandler<Void, String>() {
public Void completed(Void result, String attachment) {
try {
ByteBuffer writeBuffer = ByteBuffer.allocate(9024);
writeBuffer.put(attachment.getBytes(“UTF-8”));
writeBuffer.flip();
client.write(writeBuffer);
ByteBuffer receiveBuffer = ByteBuffer.allocate(9024);
client.read(receiveBuffer, receiveBuffer, new CompletionHandler<Integer, ByteBuffer>() {
public void completed(Integer result, ByteBuffer attachment) {
try {
client.write(ByteBuffer.wrap(“first from client”.getBytes(“UTF-8”)));
long i = 0L;
while (true) {
attachment.flip();
System.out.println(
“from server msg:” + Charset.forName(“UTF-8”).decode(attachment));
attachment = ByteBuffer.allocate(9024);
client.read(attachment).get();
client.write(ByteBuffer
.wrap((String.valueOf(i++) + “from client”).getBytes(“UTF-8”)));
Thread .sleep(3000L);
}
} catch ( Exception ex) {
ex.printStackTrace();
}
}
public void failed(Throwable thr, ByteBuffer attachment) {
thr.printStackTrace();
System.out
.println(“failed exception ” + attachment + ” detail:” + thr.getMessage());
}
});
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(“completed exception ” + attachment + ” detail:” + ex.getMessage());
}
}
public void failed(Throwable thr, String attachment) {
System.out.println(“failed exception ” + attachment + ” detail:” + thr.getMessage());
}
});
System.in.read();
服务端代码
int port = 8080;
AsynchronousServerSocketChannel server Channel = AsynchronousServerSocketChannel.open();
serverChannel.bind(new InetSocketAddress(port));
serverChannel.accept(“from server”, new CompletionHandler<AsynchronousSocketChannel, String>() {
public void completed(AsynchronousSocketChannel socketChannel, String attachment) {
try {
final ByteBuffer firstBuffer = ByteBuffer.allocate(9024);
socketChannel.read(firstBuffer).get();
firstBuffer.flip();
System.out.println(“from client ” + socketChannel.getRemoteAddress() + ” hello msg:”
+ Charset.forName(“UTF-8”).decode(firstBuffer));
socketChannel.write(ByteBuffer.wrap((“server received you request”).getBytes(“UTF-8”)));
long i = 0L;
while (true) {
final ByteBuffer clientBuffer = ByteBuffer.allocate(9024);
socketChannel.read(clientBuffer).get();
clientBuffer.flip();
System.out.println(“from client ” + socketChannel.getRemoteAddress() + ” msg:”
+ Charset.forName(“UTF-8”).decode(clientBuffer));
socketChannel.write(ByteBuffer.wrap((String.valueOf(i++) + attachment).getBytes(“UTF-8”)));
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(“completed exception ” + attachment + ” detail:” + ex.getMessage());
}
}
public void failed(Throwable thr, String attachment) {
System.out.println(“failed exception ” + attachment + ” detail:” + thr.getMessage());
}
});
System.in.read();