非阻塞服务器建立问题
这是一份关于建立非阻塞服务器的完整代码,有好几个地方不明白!!!希望高人指教。。。。以前用的都是阻塞式socket通信,第一次接触非阻塞通信,对于缓冲区,以及读写控制等都不是很懂!对于疑惑的地方我在以下代码中标出!求解答。。。(各种函数,类我都在jdk文档中看过解释,所以请勿直接贴解释,比较笨,希望得到通俗易懂的理解)
[code=Java]
package thread2;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.net.*;
import java.util.*;
public class EchoServer{
private Selector selector = null;
private ServerSocketChannel serverSocketChannel = null;
private int port = 8000;
private Charset charset=Charset.forName( "GBK ");
public EchoServer()throws
IOException{
selector = Selector.open();
serverSocketChannel= ServerSocketChannel.open();
serverSocketChannel.socket().setReuseAddress(true);
serverSocketChannel.socket().bind(new InetSocketAddress(port));
System.out.println( "服务器启动 ");
}
public void accept(){
for(;;){
try{
SocketChannel socketChannel = serverSocketChannel.accept();
System.out.println( "接收到客户连接,来自: " +
socketChannel.socket().getInetAddress() +
": " + socketChannel.socket().getPort());
socketChannel.configureBlocking(false);
ByteBuffer buffer = ByteBuffer.allocate(1024);
synchronized(gate){ //问题1:此处同步的运用不是很懂!关gate什么事???后面也有用到
selector.wakeup(); //问题2:wakeup()在此处的作用
socketChannel.register(selector,
SelectionKey.OP_READ |
SelectionKey.OP_WRITE, buffer); //问题3:buffer说是附加的项目,有什么用?