日期:2014-05-20  浏览次数:20860 次

NIO问题!!请各位大侠帮忙解决下性能问题
[color=#FF0000]我写了个简单的demo但是当客户端连接到服务时cup就上涨到50%了。[/color]
Server类:

public   class   ServerSocket   {
Selector   selector   =   null;
ServerSocketChannel   ssc   =   null;
private   Charset   charset   =   Charset.forName( "GBK ");

public   static   void   main(String[]   args)   {
ServerSocket   server=new   ServerSocket();
try   {
server.server();
}   catch   (IOException   e)   {
e.printStackTrace();
}
}

public   ServerSocket()   {
try   {
ssc   =   ServerSocketChannel.open();
java.net.ServerSocket   serversocket   =   ssc.socket();
serversocket.setReuseAddress(true);
serversocket.bind(new   InetSocketAddress( "192.168.0.159 ",   9999));
ssc.configureBlocking(false);
selector   =   Selector.open();

}   catch   (IOException   e)   {
e.printStackTrace();
}
}

public   void   server()   throws   IOException   {
ssc.register(selector,   SelectionKey.OP_ACCEPT);
while   (selector.select()> 0)   {
Set <SelectionKey>   seletorKey   =   selector.selectedKeys();
Iterator <SelectionKey>   it   =   seletorKey.iterator();
while   (it.hasNext())   {
SelectionKey   key   =   null;
try   {
key   =   it.next();
it.remove();
if   (key.isAcceptable())   {
ServerSocketChannel   ss   =   (ServerSocketChannel)
                                                                                                                                              key.channel();
SocketChannel   socketChannel   =   ss.accept();
socketChannel.configureBlocking(false);
ByteBuffer   buffer   =   ByteBuffer.allocate(1024);
socketChannel.register(selector,   SelectionKey.OP_READ
|   SelectionKey.OP_WRITE,   buffer);

}
if   (key.isReadable())   {
                                          //receive(key);
}
if   (key.isWritable())   {
//send(key);
}
}   catch   (Exception   e)   {
if   (key   !=   null)   {
key.cancel();
key.channel().close();
}
}
}
}
}
public   static   void   main(String[]   args)   {
        ServerSocket   server=new   ServerSocket();
try   {
server.server();
}   catch   (IOException   e)   {
e.printStackTrace();
}
}
}

client类:

public   class   SocketClient   {

private   SocketChannel   socketChannel   =   null;
private   ByteBuffer   sendBuffer   =   ByteBuffer.allocate(1024);