Loading [MathJax]/extensions/tex2jax.js

2014年8月19日火曜日

ノンブロッキングチャネルを試す

SocketChannel/SocketServerChannelを使ってマルチスレッドでなくても複数のクライアントに対応できるようなサーバができます。これでNode.jsはいらないですね。それにしてもByteBufferは慣れない。
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class SocketChannelClient {
public static void main(String[] args) throws IOException {
SocketChannel channel = SocketChannel.open(new InetSocketAddress("localhost", 5000));
ByteBuffer buf = ByteBuffer.allocate(1000);
channel.write(buf.wrap("Hello".getBytes()));
buf.clear();
if (channel.isConnected()) {
channel.read(buf);
}
buf.flip();
System.out.println(new String(buf.array()));
}
}
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.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class SocketChannelServer {
private static Selector selector = null;
public static void main(String[] args) {
new SocketChannelServer().run();
}
public void run() {
ServerSocketChannel server = null;
try {
selector = Selector.open();
server = ServerSocketChannel.open();
server.configureBlocking(false);
server.bind(new InetSocketAddress(5000));
server.register(selector, SelectionKey.OP_ACCEPT);
while (selector.select() > 0) {
for (Iterator it = selector.selectedKeys().iterator(); it.hasNext();) {
SelectionKey key = (SelectionKey) it.next();
it.remove();
if (key.isAcceptable()) {
SocketChannel channel = server.accept();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
} else if(key.isReadable() && key.isWritable()){
ByteBuffer buf = ByteBuffer.allocate(1000);
SocketChannel channel = (SocketChannel) key.channel();
channel.read(buf);
//System.out.println(new String(buf.array()));
buf.flip();
channel.write(buf);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

0 件のコメント: