📄 acceptor.java
字号:
package com.ec.generalserver;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.ServerSocketChannel;
import java.util.*;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
public class Acceptor
{
private String listen_ip;
private int listen_port;
private List allow_ip = null;
private int max_conn = -1;
private ServerSocketChannel listen_channel;
private Stack use_conn = new Stack();
private boolean is_init = false;
public Acceptor(String ip,int port)
{
listen_ip = ip;
listen_port = port;
};
public void setAllowIP(List ips)
{
allow_ip = ips;
}
public void setMaxConn(int maxconn)
{
max_conn = maxconn;
}
public void init() throws Exception
{
synchronized(this)
{
if ( is_init )
return;
listen_channel = ServerSocketChannel.open();
ServerSocket ss = listen_channel.socket();
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(listen_ip,listen_port));
listen_channel.configureBlocking(false);
is_init = true;
System.out.println("listen at :" + listen_ip + " port :" + listen_port);
}
}
public void register(Selector selector) throws Exception
{
listen_channel.register(selector,SelectionKey.OP_ACCEPT,this);
}
public Connection comeConnection() throws Exception
{
SocketChannel client = listen_channel.accept();
if ( client == null )
{
System.out.println("accept return null");
return null;
}
String remote = client.socket().getInetAddress().getHostAddress();
if ( allow_ip!=null && !allow_ip.contains(remote) )
{
System.out.println("not allow ip addr :" + remote + ",reject connection" );
client.close();
return null;
}
if ( max_conn>0 && use_conn.size()>=max_conn )
{
System.out.println("max client arrived, reject connection");
client.close();
return null;
}
System.out.println("accept connection from :" + remote);
client.configureBlocking(false);
Connection conn = new Connection();
conn.init(this,client);
use_conn.push(conn);
return conn;
};
public void recycle(Connection conn)
{
use_conn.remove(conn);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -