Posted By:
rick_murphy
Posted On:
Wednesday, February 11, 2004 10:18 PM
i create a ServerSocketChannel to listen the clients' connection,and regist it to a selector. but ,after i accepting the connection by "ServerSocketChannel.accept()" ,the key which i registed ServerSocketChannel on selector keep alive for acceptable, caused the code for acceptable always run . why do SelectionKey.isAcceptable() still be true after i accepting the connection? i use java 2 Standard Edition SDK 1.4.2_01 any response will be appreciated! public void start(){ try{ ServerSocketChannel ssChannel = ServerSocketChannel.open(); ssChannel.configureBlocking(false); ssChannel.socket().bind(new Inet
More>>
i create a ServerSocketChannel to listen the clients' connection,and regist it
to a selector. but ,after i accepting the connection by "ServerSocketChannel.accept()"
,the key which i registed ServerSocketChannel on selector keep alive for acceptable,
caused the code for acceptable always run .
why do SelectionKey.isAcceptable() still be true after i accepting the connection?
i use java 2 Standard Edition SDK 1.4.2_01
any response will be appreciated!
public void start(){
try{
ServerSocketChannel ssChannel = ServerSocketChannel.open();
ssChannel.configureBlocking(false);
ssChannel.socket().bind(new InetSocketAddress(InetAddress.getLocalHost(),port));
System.out.println("Server started at localhost "+Integer.toString(port));
Selector selector = Selector.open();
ssChannel.register(selector,SelectionKey.OP_ACCEPT);
while(true){
if(selector.select()>0){
for(Iterator it = selector.keys().iterator();it.hasNext();){
SelectionKey key = (SelectionKey)it.next();
System.out.println(key.toString());
if(key.isAcceptable()){
SocketChannel sChannel = ssChannel.accept();
sChannel.configureBlocking(false);
String ip = sChannel.socket().getRemoteSocketAddress().toString();
System.out.println(ip+" trying to connect...");
if(isPermitedIP(ip)){
SelectionKey readKey = sChannel.register(selector,SelectionKey.OP_READ);
readKey.attach(sChannel);
socketMap.put(sChannel,sChannel);
System.out.println(ip+" authenticated!");
}else{
sChannel.close();
System.out.println(ip+" refused!");
}
}else if(key.isReadable()){
ByteBuffer bytes = ByteBuffer.allocate(BUFFER_SIZE);
long nbytes = 0;
SocketChannel s = (SocketChannel)key.attachment();
nbytes = s.read(bytes);
if(nbytes>0){
bytes.flip();
String message = new String(bytes.array());
message = message.trim();
String ip = s.socket().getRemoteSocketAddress().toString();
System.out.println(ip+": "+message);
String response = socketResponsor.response(message);
s.write(ByteBuffer.wrap(response.getBytes()));
}else if(nbytes==-1){
socketMap.remove(s);
s.keyFor(selector).cancel();
s.close();
}
}
}
}
}
}catch(java.io.IOException e){
e.printStackTrace();
}
}
<<Less