下面列出了java.nio.channels.ClosedSelectorException#java.nio.channels.ServerSocketChannel 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void main(String[] args) throws Exception {
boolean keepAlive = false;
String prop = System.getProperty("com.sun.CORBA.transport.enableTcpKeepAlive");
if (prop != null)
keepAlive = !"false".equalsIgnoreCase(prop);
DefaultSocketFactoryImpl sfImpl = new DefaultSocketFactoryImpl();
ORBImpl orb = new ORBImpl();
orb.set_parameters(null);
sfImpl.setORB(orb);
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(0));
InetSocketAddress isa = new InetSocketAddress("localhost", ssc.socket().getLocalPort());
Socket s = sfImpl.createSocket("ignore", isa);
System.out.println("Received factory socket" + s);
if (keepAlive != s.getKeepAlive())
throw new RuntimeException("KeepAlive value not honoured in CORBA socket");
}
/**
* Initialize the selector
* @return The selector we'll be monitoring
* @throws IOException When the selector can't be created (Usually when the port is already in use)
*/
private Selector initSelector() throws IOException {
// Create a new selector
Selector socketSelector = SelectorProvider.provider().openSelector();
// Create a new non-blocking server socket channel
this.serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
// Bind the server socket to the specified address and port
InetSocketAddress isa = new InetSocketAddress(this.port);
serverChannel.socket().bind(isa);
// Register the server socket channel, indicating an interest in
// accepting new connections
serverChannel.register(socketSelector, SelectionKey.OP_ACCEPT);
log.info("Listening on port " + this.port + "...");
return socketSelector;
}
private static void handleNewConnection(
SSLContext sslContext, Selector selector, ServerSocketChannel serverChannel)
throws IOException {
// accept new connection
SocketChannel rawChannel = serverChannel.accept();
rawChannel.configureBlocking(false);
// wrap raw channel in TlsChannel
TlsChannel tlsChannel =
ServerTlsChannel.newBuilder(rawChannel, sslContext).withRunTasks(false).build();
/*
* Wrap raw channel with a TlsChannel. Note that the raw channel is registered in the selector
* and the TlsChannel put as an attachment register the channel for reading, because TLS
* connections are initiated by clients.
*/
SelectionKey newKey = rawChannel.register(selector, SelectionKey.OP_READ);
newKey.attach(tlsChannel);
}
public static void main(String args[]) throws Exception {
InetAddress iaddr = InetAddress.getLocalHost();
try ( ServerSocket ss = new ServerSocket(0);
Socket s1 = new Socket(iaddr, ss.getLocalPort());
Socket s2 = ss.accept() ) {
test(s1, s2, "Testing NET");
}
// check the NIO socket adapter
try (ServerSocketChannel sc = ServerSocketChannel.open().bind(null);
SocketChannel s1 = SocketChannel.open(
new InetSocketAddress(iaddr, sc.socket().getLocalPort()));
SocketChannel s2 = sc.accept() ) {
test(s1.socket(), s2.socket(), "Testing NIO");
}
if (failed) {
throw new RuntimeException("Failed: check output");
}
}
@Override
public void start(int port) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress("0.0.0.0", port));
serverSocketChannel.configureBlocking(false);
acceptReactor = new Reactor();
acceptReactor.start();
subReactors = new Reactor[5];
for (int i = 0; i < subReactors.length; i++) {
subReactors[i] = new Reactor();
subReactors[i].start();
}
Acceptor acceptor = new Acceptor(subReactors);
acceptReactor.register(serverSocketChannel, SelectionKey.OP_ACCEPT, acceptor);
}
public static void main(String args[]) throws Exception {
InetAddress iaddr = InetAddress.getLocalHost();
try ( ServerSocket ss = new ServerSocket(0);
Socket s1 = new Socket(iaddr, ss.getLocalPort());
Socket s2 = ss.accept() ) {
test(s1, s2, "Testing NET");
}
// check the NIO socket adapter
try (ServerSocketChannel sc = ServerSocketChannel.open().bind(null);
SocketChannel s1 = SocketChannel.open(
new InetSocketAddress(iaddr, sc.socket().getLocalPort()));
SocketChannel s2 = sc.accept() ) {
test(s1.socket(), s2.socket(), "Testing NIO");
}
if (failed) {
throw new RuntimeException("Failed: check output");
}
}
/**
* Creates a port listening server socket
*/
public GfxdTServerSocket(InetSocketAddress bindAddress, boolean blocking,
boolean clientBlocking, SocketParameters params)
throws TTransportException {
this.clientBlocking = clientBlocking;
this.socketParams = params;
try {
// Make server socket
this.serverSockChannel = ServerSocketChannel.open();
this.serverSockChannel.configureBlocking(blocking);
ServerSocket socket = this.serverSockChannel.socket();
// Prevent 2MSL delay problem on server restarts
socket.setReuseAddress(true);
// Bind to listening port
socket.bind(bindAddress);
} catch (IOException ioe) {
throw new TTransportException(TTransportException.NOT_OPEN,
"Could not bind to host:port " + bindAddress.toString(), ioe);
}
}
public static void main(String args[]) throws Exception {
InetAddress iaddr = InetAddress.getLocalHost();
try ( ServerSocket ss = new ServerSocket(0);
Socket s1 = new Socket(iaddr, ss.getLocalPort());
Socket s2 = ss.accept() ) {
test(s1, s2, "Testing NET");
}
// check the NIO socket adapter
try (ServerSocketChannel sc = ServerSocketChannel.open().bind(null);
SocketChannel s1 = SocketChannel.open(
new InetSocketAddress(iaddr, sc.socket().getLocalPort()));
SocketChannel s2 = sc.accept() ) {
test(s1.socket(), s2.socket(), "Testing NIO");
}
if (failed) {
throw new RuntimeException("Failed: check output");
}
}
private void init() {
ServerSocketChannel socketChannel = processor.javaChannel();
ServerSocket javaSocket = socketChannel.socket();
try {
if (serverConfig.getReceiveBufferSize() != null) {
javaSocket.setReceiveBufferSize(serverConfig.getReceiveBufferSize());
}
if (serverConfig.getReuseAddress() != null) {
javaSocket.setReuseAddress(serverConfig.getReuseAddress());
}
} catch (SocketException e) {
throw new NioException("config channel error:" + e.getMessage(), e);
}
}
/**
* Creates a port listening server socket
*/
public GfxdTServerSocket(InetSocketAddress bindAddress, boolean blocking,
boolean clientBlocking, SocketParameters params)
throws TTransportException {
this.clientBlocking = clientBlocking;
this.socketParams = params;
try {
// Make server socket
this.serverSockChannel = ServerSocketChannel.open();
this.serverSockChannel.configureBlocking(blocking);
ServerSocket socket = this.serverSockChannel.socket();
// Prevent 2MSL delay problem on server restarts
socket.setReuseAddress(true);
// Bind to listening port
socket.bind(bindAddress);
} catch (IOException ioe) {
throw new TTransportException(TTransportException.NOT_OPEN,
"Could not bind to host:port " + bindAddress.toString(), ioe);
}
}
private void handSelectionKeyException(final SelectionKey selectionKey,Exception e){
SelectableChannel channel = selectionKey.channel();
if(channel instanceof ServerSocketChannel){
RpcNioAcceptor acceptor = acceptorCache.get(channel);
if(acceptor!=null){
logger.error("acceptor "+acceptor.getHost()+":"+acceptor.getPort()+" selection error "+e.getClass()+" "+e.getMessage()+" start to shutdown");
this.fireNetListeners(acceptor, e);
acceptor.stopService();
}
}else{
RpcNioConnector connector = connectorCache.get(channel);
if(connector!=null){
logger.error("connector "+connector.getHost()+":"+connector.getPort()+" selection error "+e.getClass()+" "+e.getMessage()+" start to shutdown");
this.fireNetListeners(connector, e);
connector.stopService();
}
}
this.logState();
}
public static void main(String args[]) throws Exception {
InetAddress iaddr = InetAddress.getLocalHost();
try ( ServerSocket ss = new ServerSocket(0);
Socket s1 = new Socket(iaddr, ss.getLocalPort());
Socket s2 = ss.accept() ) {
test(s1, s2, "Testing NET");
}
// check the NIO socket adapter
try (ServerSocketChannel sc = ServerSocketChannel.open().bind(null);
SocketChannel s1 = SocketChannel.open(
new InetSocketAddress(iaddr, sc.socket().getLocalPort()));
SocketChannel s2 = sc.accept() ) {
test(s1.socket(), s2.socket(), "Testing NIO");
}
if (failed) {
throw new RuntimeException("Failed: check output");
}
}
public static void main(String[] args) throws Exception {
boolean keepAlive = false;
String prop = System.getProperty("com.sun.CORBA.transport.enableTcpKeepAlive");
if (prop != null)
keepAlive = !"false".equalsIgnoreCase(prop);
DefaultSocketFactoryImpl sfImpl = new DefaultSocketFactoryImpl();
ORBImpl orb = new ORBImpl();
orb.set_parameters(null);
sfImpl.setORB(orb);
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(0));
InetSocketAddress isa = new InetSocketAddress("localhost", ssc.socket().getLocalPort());
Socket s = sfImpl.createSocket("ignore", isa);
System.out.println("Received factory socket" + s);
if (keepAlive != s.getKeepAlive())
throw new RuntimeException("KeepAlive value not honoured in CORBA socket");
}
public static void main(String[] args) throws Exception {
boolean keepAlive = false;
String prop = System.getProperty("com.sun.CORBA.transport.enableTcpKeepAlive");
if (prop != null)
keepAlive = !"false".equalsIgnoreCase(prop);
DefaultSocketFactoryImpl sfImpl = new DefaultSocketFactoryImpl();
ORBImpl orb = new ORBImpl();
orb.set_parameters(null);
sfImpl.setORB(orb);
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(0));
InetSocketAddress isa = new InetSocketAddress("localhost", ssc.socket().getLocalPort());
Socket s = sfImpl.createSocket("ignore", isa);
System.out.println("Received factory socket" + s);
if (keepAlive != s.getKeepAlive())
throw new RuntimeException("KeepAlive value not honoured in CORBA socket");
}
private ConnectionResetByPeerServer(int port) {
super(1);
this.port = port;
try {
server = ServerSocketChannel.open();
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
private void onSelectAccept(SelectionKey key) throws IOException {
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel sc = ssc.accept();
if (sc != null) {
closeConnection = false;
pendingWrites.clear();
input.clear();
sc.configureBlocking(false);
sc.register(key.selector(), SelectionKey.OP_READ);
socketChannel = sc;
enableNewConnections(false);
onDebuggerConnected();
}
}
/**
* Start the server and begin accepting incoming connections.
*
*/
@Override
public void startProcessing() {
try{
this_mon.enter();
if( !isRunning() ) {
try {
server_channel = ServerSocketChannel.open();
server_channel.socket().setReuseAddress( true );
if( receive_buffer_size > 0 ) server_channel.socket().setReceiveBufferSize( receive_buffer_size );
server_channel.socket().bind( bind_address, 1024 );
if (Logger.isEnabled()) Logger.log(new LogEvent(LOGID, "TCP incoming server socket " + bind_address));
AEThread accept_thread = new AEThread( "VServerSelector:port" + bind_address.getPort() ) {
@Override
public void runSupport() {
accept_loop();
}
};
accept_thread.setDaemon( true );
accept_thread.start();
}
catch( Throwable t ) {
Debug.out( t );
Logger.log(new LogAlert(LogAlert.UNREPEATABLE, "ERROR, unable to bind TCP incoming server socket to " +bind_address.getPort(), t));
}
last_accept_time = SystemTime.getCurrentTime(); //init to now
}
}finally{
this_mon.exit();
}
}
@Override
public ClientListener getClientConnection(SocketChannel sc, ServerSocketChannel ssc)
{
ClientListener client;
if (authToken == null) {
client = new UnidentifiedClient();
} else {
AuthClient authClient = new AuthClient();
authClient.setToken(authToken);
client = authClient;
}
return client;
}
public RpcNioAcceptor(AbstractRpcNioSelector selector){
try {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
this.selector = selector;
} catch (IOException e) {
this.handleNetException(e);
}
}
TlsService(Station station, InetSocketAddress localAddress,
ServerSocketChannel serverChannel, IpService service,
IpSettings ipSettings) {
this.station = station;
this.localAddress = localAddress;
this.serverChannel = serverChannel;
this.service = service;
this.ipSettings = ipSettings;
}
private void acceptOP(SelectionKey key, Selector selector) throws IOException {
ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = serverChannel.accept();
socketChannel.configureBlocking(false);
System.out.println("Incoming connection from: " + socketChannel.getRemoteAddress());
// write an welcome message
socketChannel.write(ByteBuffer.wrap("Hello!\n".getBytes("UTF-8")));
// register channel with selector for further I/O
keepDataTrack.put(socketChannel, new ArrayList<byte[]>());
socketChannel.register(selector, SelectionKey.OP_READ);
}
private static void nio2() {
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(8080));
SocketChannel socketChannel = serverSocketChannel.accept();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (socketChannel.read(byteBuffer) != -1) {
byteBuffer.flip();
socketChannel.write(byteBuffer);
byteBuffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @tests ServerSocketChannel#socket().getSoTimeout()
*/
public void test_accept_SOTIMEOUT() throws IOException {
// Regression test for Harmony-707
// The timeout actually used may be different from the one set due to
// rounding by the Linux Kernel (see sock_set_timeout() in net/core/sock.c).
// getSoTimeout() can return a different value from the one set with
// setSoTimeout(). Consequently we do not check for equality with what was
// set.
ServerSocketChannel sc = ServerSocketChannel.open();
try {
sc.socket().bind(null);
// Non blocking mode, accept() will return NULL since there are no pending connections.
sc.configureBlocking(false);
ServerSocket ss = sc.socket();
int defaultTimeout = ss.getSoTimeout();
assertEquals(0, defaultTimeout);
// The timeout value is unimportant, providing it is large enough to be accepted
// by the Kernel as distinct from the default.
final int SO_TIMEOUT = 200;
ss.setSoTimeout(SO_TIMEOUT);
int nonDefaultTimeout = ss.getSoTimeout();
assertTrue(nonDefaultTimeout != defaultTimeout);
SocketChannel client = sc.accept();
assertNull(client);
// Confirm the timeout was unchanged.
assertEquals(nonDefaultTimeout, ss.getSoTimeout());
} finally {
sc.close();
}
}
/**
* Opens (or reopens) the "debug selected" port and listen for connections.
* @return true if the port was opened successfully.
* @throws IOException
*/
private boolean reopenDebugSelectedPort() throws IOException {
Log.d("ddms", "reopen debug-selected port: " + mNewDebugSelectedPort);
if (mDebugSelectedChan != null) {
mDebugSelectedChan.close();
}
mDebugSelectedChan = ServerSocketChannel.open();
mDebugSelectedChan.configureBlocking(false); // required for Selector
InetSocketAddress addr = new InetSocketAddress(
InetAddress.getByName("localhost"), //$NON-NLS-1$
mNewDebugSelectedPort);
mDebugSelectedChan.socket().setReuseAddress(true); // enable SO_REUSEADDR
try {
mDebugSelectedChan.socket().bind(addr);
if (mSelectedClient != null) {
mSelectedClient.update(Client.CHANGE_PORT);
}
mDebugSelectedChan.register(mSelector, SelectionKey.OP_ACCEPT, this);
return true;
} catch (java.net.BindException e) {
displayDebugSelectedBindError(mNewDebugSelectedPort);
// do not attempt to reopen it.
mDebugSelectedChan = null;
mNewDebugSelectedPort = -1;
return false;
}
}
public static void main(String[] args) throws IOException {
// 1、创建选择器
Selector selector = Selector.open();
// 2、将通道注册到选择器上
ServerSocketChannel ssChannel = ServerSocketChannel.open();
// 设置非阻塞
ssChannel.configureBlocking(false);
ssChannel.register(selector, SelectionKey.OP_ACCEPT);
// 3、监听事件
ServerSocket serverSocket = ssChannel.socket();
serverSocket.bind(new InetSocketAddress("127.0.0.1", 8080));
while (true) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = keys.iterator();
// 5、事件循环
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
// 4、获取到达的事件
if (key.isAcceptable()) {
ServerSocketChannel ssChannel1 = (ServerSocketChannel) key.channel();
// 服务器会为每个新连接创建一个 SocketChannel
SocketChannel socketChannel = ssChannel1.accept();
socketChannel.configureBlocking(false);
// 这个新连接主要用于从客户端读取数据
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
SocketChannel sChannel = (SocketChannel) key.channel();
System.out.println(readDataFromSocketChannel(sChannel));
sChannel.close();
}
keyIterator.remove();
}
}
}
@Override
public int getPort() {
// Return the port for the key listening for accepts
for(SelectionKey key : selector.keys()){
if (key.isValid()) {
final Channel channel = key.channel();
if (channel instanceof ServerSocketChannel) {
return ((ServerSocketChannel)channel).socket().getLocalPort();
}
}
}
return 0;
}
/**
* Regression test for Harmony-1947.
*/
public void test_finishConnect() throws Exception {
SocketAddress address = new InetSocketAddress("localhost", 0);
ServerSocketChannel theServerChannel = ServerSocketChannel.open();
ServerSocket serversocket = theServerChannel.socket();
serversocket.setReuseAddress(true);
// Bind the socket
theServerChannel.socket().bind(address);
boolean doneNonBlockingConnect = false;
// Loop so that we make sure we're definitely testing finishConnect()
while (!doneNonBlockingConnect) {
channel1 = SocketChannel.open();
// Set the SocketChannel to non-blocking so that connect(..) does
// not block
channel1.configureBlocking(false);
boolean connected = channel1.connect(new InetSocketAddress("localhost",serversocket.getLocalPort()));
if (!connected) {
// Now set the SocketChannel back to blocking so that
// finishConnect() blocks.
channel1.configureBlocking(true);
doneNonBlockingConnect = channel1.finishConnect();
}
if (doneNonBlockingConnect) {
tryFinish();
}
channel1.close();
}
if (!serversocket.isClosed()) {
serversocket.close();
}
}
public void startup() throws IOException {
selector = Selector.open();
server = ServerSocketChannel.open();
server.configureBlocking(false);
server.socket().setReuseAddress(true);
server.socket().bind(srcAddr);
server.register(selector, SelectionKey.OP_ACCEPT);
new Thread(this).start();
}
private void doInitSocketServerTcp() throws IOException {
dirtyServerTcp = ServerSocketChannel.open();
dirtyServerTcp.configureBlocking(false);
// Bind the server socket to the specified address and port
InetSocketAddress isa = new InetSocketAddress(CLIENT_HOST, CLIENT_PORT);
dirtyServerTcp.bind(isa);
}
@Test(expected = BindException.class)
public void bindMultiTimes() throws InterruptedException, IOException {
int port = 11911;
List<ServerSocketChannel> serverSockets = new ArrayList<>(2);
for (int i = 0; i < 2; i++) {
ServerSocketChannel serverSocket = ServerSocketChannel.open();
serverSockets.add(serverSocket);
serverSocket.socket().bind(new InetSocketAddress(port));
}
Thread.sleep(10 * 1000);
System.out.println("done.");
}