2014年9月27日土曜日

AsynchronousSocketChannelとAsynchronousServerSocketChannelを使ったサンプル

AsynchronousSocketChannelとAsynchronousServerSocketChannelを使って簡単なサーバクライアントサンプルを書いてみました。 Futureが返却されるので非同期タスクを細かく制御できるようです。これだけ長いクラスを使うのだから、それだけの恩恵は欲しいですね。
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
public class AsynchronousSocketChannelClient {
public static void main(String[] args) {
try (AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();) {
channel.connect(new InetSocketAddress("localhost",5000)).get();
channel.write(ByteBuffer.wrap("Hello".getBytes())).get();
} catch (IOException | InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class AsynchronousSocketChannelServer {
public static void main(String[] args) {
try (AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open();) {
server.bind(new InetSocketAddress(5000));
while (true) {
Future<AsynchronousSocketChannel> socket = server.accept();
try (AsynchronousSocketChannel channel = socket.get();) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
Future<Integer> result = channel.read(buffer);
Integer i = result.get();
System.out.println("Read:" + i);
buffer.flip();
System.out.println(new String(buffer.array()));
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

0 件のコメント: