「Java入門」サーバー側Java NIO socketのサンプルプログラム

Javaコード:
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.Set;

public class HTTPSocket {

public static void main(String[] args) throws IOException {

Selector selector=Selector.open(); //セレクターをオープン

//サービスリッスンチャネルをオープン
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();

//ノンプロキングに設定
serverSocketChannel.configureBlocking(false);

//リスナーチャネルがセレクタを受け入れるようにマークを登録
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

serverSocketChannel.socket().bind(new InetSocketAddress(8080));

SocketChannel channel=null;

boolean b=true;//書き込むことをマーク

StringBuffer buffer=new StringBuffer();

while(true){

selector.select();//最少一つのキー

Set<SelectionKey> selectionKeys=selector.selectedKeys();//キーを取得

for(SelectionKey selectionKey:selectionKeys){

if(selectionKey.isAcceptable()){

channel=serverSocketChannel.accept();

channel.configureBlocking(false);

channel.register(selector, SelectionKey.OP_READ);

selectionKeys.remove(selectionKey);

}else{

if(selectionKey.isReadable()){//読む可能

ByteBuffer bytebuffer=ByteBuffer.allocate(1);
channel.read(bytebuffer);
bytebuffer.position(0);

char c=(char)bytebuffer.get();
buffer.append(c);

if(c==’\n’){

System.out.println(buffer);
b=true;
if(!selectionKey.isWritable())
channel.register(selector, SelectionKey.OP_WRITE);
buffer=new StringBuffer();
}

}
else if(selectionKey.isWritable()){//書く可能

if(b){
ByteBuffer bytebuff=ByteBuffer.wrap(“こんにちは\n".getBytes());
bytebuff.position(0);
channel.write(bytebuff);
b=false;
if(!selectionKey.isReadable())
channel.register(selector, SelectionKey.OP_READ);
}

}

}

}

}

}
}

Java

Posted by arkgame