List of usage examples for java.nio.channels ServerSocketChannel configureBlocking
public final SelectableChannel configureBlocking(boolean block) throws IOException
From source file:com.web.server.WebServer.java
/** * This is the start of the all the services in web server * @param args//from w ww . j a va 2 s . c om * @throws IOException * @throws SAXException */ public static void main(String[] args) throws IOException, SAXException { Hashtable urlClassLoaderMap = new Hashtable(); Hashtable executorServicesMap = new Hashtable(); Hashtable ataMap = new Hashtable<String, ATAConfig>(); Hashtable messagingClassMap = new Hashtable(); ConcurrentHashMap servletMapping = new ConcurrentHashMap(); DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() { protected void loadRules() { // TODO Auto-generated method stub try { loadXMLRules(new InputSource(new FileInputStream("./config/serverconfig-rules.xml"))); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); Digester serverdigester = serverdigesterLoader.newDigester(); final ServerConfig serverconfig = (ServerConfig) serverdigester .parse(new InputSource(new FileInputStream("./config/serverconfig.xml"))); DigesterLoader messagingdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() { protected void loadRules() { // TODO Auto-generated method stub try { loadXMLRules(new InputSource(new FileInputStream("./config/messagingconfig-rules.xml"))); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); Digester messagingdigester = messagingdigesterLoader.newDigester(); MessagingElem messagingconfig = (MessagingElem) messagingdigester .parse(new InputSource(new FileInputStream("./config/messaging.xml"))); //System.out.println(messagingconfig); ////System.out.println(serverconfig.getDeploydirectory()); PropertyConfigurator.configure("log4j.properties"); /*MemcachedClient cache=new MemcachedClient( new InetSocketAddress("localhost", 1000));*/ // Store a value (async) for one hour //c.set("someKey", 36, new String("arun")); // Retrieve a value. System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory"); System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming"); ExecutorService executor = java.util.concurrent.Executors.newCachedThreadPool(); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = null; try { name = new ObjectName("com.web.server:type=WarDeployer"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } WarDeployer warDeployer = new WarDeployer(serverconfig.getDeploydirectory(), serverconfig.getFarmWarDir(), serverconfig.getClustergroup(), urlClassLoaderMap, executorServicesMap, messagingClassMap, servletMapping, messagingconfig, sessionObjects); warDeployer.setPriority(MIN_PRIORITY); try { mbs.registerMBean(warDeployer, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //warDeployer.start(); executor.execute(warDeployer); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.bind(new InetSocketAddress("0.0.0.0", Integer.parseInt(serverconfig.getPort()))); serverSocketChannel.configureBlocking(false); final byte[] shutdownBt = new byte[50]; WebServerRequestProcessor webserverRequestProcessor = new WebServer().new WebServerRequestProcessor( servletMapping, urlClassLoaderMap, serverSocketChannel, serverconfig.getDeploydirectory(), Integer.parseInt(serverconfig.getShutdownport()), 1); webserverRequestProcessor.setPriority(MIN_PRIORITY); try { name = new ObjectName("com.web.server:type=WebServerRequestProcessor"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(webserverRequestProcessor, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //webserverRequestProcessor.start(); executor.execute(webserverRequestProcessor); for (int i = 0; i < 10; i++) { WebServerRequestProcessor webserverRequestProcessor1 = new WebServer().new WebServerRequestProcessor( servletMapping, urlClassLoaderMap, serverSocketChannel, serverconfig.getDeploydirectory(), Integer.parseInt(serverconfig.getShutdownport()), 2); webserverRequestProcessor1.setPriority(MIN_PRIORITY); try { name = new ObjectName("com.web.server:type=WebServerRequestProcessor" + (i + 1)); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(webserverRequestProcessor1, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } executor.execute(webserverRequestProcessor1); } ServerSocketChannel serverSocketChannelServices = ServerSocketChannel.open(); serverSocketChannelServices .bind(new InetSocketAddress("0.0.0.0", Integer.parseInt(serverconfig.getServicesport()))); serverSocketChannelServices.configureBlocking(false); ExecutorServiceThread executorService = new ExecutorServiceThread(serverSocketChannelServices, executorServicesMap, Integer.parseInt(serverconfig.getShutdownport()), ataMap, urlClassLoaderMap, serverconfig.getDeploydirectory(), serverconfig.getServicesdirectory(), serverconfig.getEarservicesdirectory(), serverconfig.getNodesport()); try { name = new ObjectName("com.web.services:type=ExecutorServiceThread"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(executorService, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //executorService.start(); executor.execute(executorService); for (int i = 0; i < 10; i++) { ExecutorServiceThread executorService1 = new ExecutorServiceThread(serverSocketChannelServices, executorServicesMap, Integer.parseInt(serverconfig.getShutdownport()), ataMap, urlClassLoaderMap, serverconfig.getDeploydirectory(), serverconfig.getServicesdirectory(), serverconfig.getEarservicesdirectory(), serverconfig.getNodesport()); try { name = new ObjectName("com.web.services:type=ExecutorServiceThread" + (i + 1)); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(executorService1, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } executor.execute(executorService1); } WebServerHttpsRequestProcessor webserverHttpsRequestProcessor = new WebServer().new WebServerHttpsRequestProcessor( servletMapping, urlClassLoaderMap, Integer.parseInt(serverconfig.getHttpsport()), serverconfig.getDeploydirectory(), Integer.parseInt(serverconfig.getShutdownport()), serverconfig.getHttpscertificatepath(), serverconfig.getHttpscertificatepasscode(), 1); try { name = new ObjectName("com.web.server:type=WebServerHttpsRequestProcessor"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(webserverHttpsRequestProcessor, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } webserverHttpsRequestProcessor.setPriority(MAX_PRIORITY); //webserverRequestProcessor.start(); executor.execute(webserverHttpsRequestProcessor); /* for(int i=0;i<2;i++){ webserverHttpsRequestProcessor=new WebServer().new WebServerHttpsRequestProcessor(urlClassLoaderMap,Integer.parseInt(serverconfig.getHttpsport())+(i+1),serverconfig.getDeploydirectory(),Integer.parseInt(serverconfig.getShutdownport()),serverconfig.getHttpscertificatepath(),serverconfig.getHttpscertificatepasscode(),1); try { name = new ObjectName("com.web.server:type=WebServerHttpsRequestProcessor"+(i+1)); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(webserverHttpsRequestProcessor, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } executor.execute(webserverHttpsRequestProcessor); }*/ /*ATAServer ataServer=new ATAServer(serverconfig.getAtaaddress(),serverconfig.getAtaport(),ataMap); try { name = new ObjectName("com.web.services:type=ATAServer"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(ataServer, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ataServer.start();*/ /*ATAConfigClient ataClient=new ATAConfigClient(serverconfig.getAtaaddress(),serverconfig.getAtaport(),serverconfig.getServicesport(),executorServicesMap); try { name = new ObjectName("com.web.services:type=ATAConfigClient"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(ataClient, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ataClient.start();*/ MessagingServer messageServer = new MessagingServer(serverconfig.getMessageport(), messagingClassMap); try { name = new ObjectName("com.web.messaging:type=MessagingServer"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(messageServer, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //messageServer.start(); executor.execute(messageServer); RandomQueueMessagePicker randomqueuemessagepicker = new RandomQueueMessagePicker(messagingClassMap); try { name = new ObjectName("com.web.messaging:type=RandomQueueMessagePicker"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(randomqueuemessagepicker, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //randomqueuemessagepicker.start(); executor.execute(randomqueuemessagepicker); RoundRobinQueueMessagePicker roundrobinqueuemessagepicker = new RoundRobinQueueMessagePicker( messagingClassMap); try { name = new ObjectName("com.web.messaging:type=RoundRobinQueueMessagePicker"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(roundrobinqueuemessagepicker, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //roundrobinqueuemessagepicker.start(); executor.execute(roundrobinqueuemessagepicker); TopicMessagePicker topicpicker = new TopicMessagePicker(messagingClassMap); try { name = new ObjectName("com.web.messaging:type=TopicMessagePicker"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(topicpicker, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //topicpicker.start(); executor.execute(topicpicker); try { name = new ObjectName("com.web.server:type=SARDeployer"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } SARDeployer sarDeployer = SARDeployer.newInstance(serverconfig.getDeploydirectory()); try { mbs.registerMBean(sarDeployer, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } executor.execute(sarDeployer); /*try { mbs.invoke(name, "startDeployer", null, null); } catch (InstanceNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (ReflectionException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (MBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } */ System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory"); System.setProperty(Context.PROVIDER_URL, "rmi://localhost:" + serverconfig.getServicesregistryport()); ; Registry registry = LocateRegistry.createRegistry(Integer.parseInt(serverconfig.getServicesregistryport())); /*JarDeployer jarDeployer=new JarDeployer(registry,serverconfig.getServicesdirectory(), serverconfig.getServiceslibdirectory(),serverconfig.getCachedir(),executorServicesMap, urlClassLoaderMap); try { name = new ObjectName("com.web.server:type=JarDeployer"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(jarDeployer, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //jarDeployer.start(); executor.execute(jarDeployer);*/ EARDeployer earDeployer = new EARDeployer(registry, serverconfig.getEarservicesdirectory(), serverconfig.getDeploydirectory(), executorServicesMap, urlClassLoaderMap, serverconfig.getCachedir(), warDeployer); try { name = new ObjectName("com.web.server:type=EARDeployer"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(earDeployer, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //earDeployer.start(); executor.execute(earDeployer); JVMConsole jvmConsole = new JVMConsole(Integer.parseInt(serverconfig.getJvmConsolePort())); try { name = new ObjectName("com.web.server:type=JVMConsole"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(jvmConsole, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } executor.execute(jvmConsole); ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); XMLDeploymentScanner xmlDeploymentScanner = new XMLDeploymentScanner(serverconfig.getDeploydirectory(), serverconfig.getServiceslibdirectory()); exec.scheduleAtFixedRate(xmlDeploymentScanner, 0, 1000, TimeUnit.MILLISECONDS); EmbeddedJMS embeddedJMS = null; try { embeddedJMS = new EmbeddedJMS(); embeddedJMS.start(); } catch (Exception ex) { // TODO Auto-generated catch block ex.printStackTrace(); } EJBDeployer ejbDeployer = new EJBDeployer(serverconfig.getServicesdirectory(), registry, Integer.parseInt(serverconfig.getServicesregistryport()), embeddedJMS); try { name = new ObjectName("com.web.server:type=EJBDeployer"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(ejbDeployer, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //jarDeployer.start(); executor.execute(ejbDeployer); new Thread() { public void run() { try { ServerSocket serverSocket = new ServerSocket(Integer.parseInt(serverconfig.getShutdownport())); while (true) { Socket sock = serverSocket.accept(); InputStream istream = sock.getInputStream(); istream.read(shutdownBt); String shutdownStr = new String(shutdownBt); String[] shutdownToken = shutdownStr.split("\r\n\r\n"); //System.out.println(shutdownStr); if (shutdownToken[0].startsWith("shutdown WebServer")) { synchronized (shutDownObject) { shutDownObject.notifyAll(); } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { System.out.println("IN shutdown Hook"); synchronized (shutDownObject) { shutDownObject.notifyAll(); } } })); try { synchronized (shutDownObject) { shutDownObject.wait(); } executor.shutdownNow(); serverSocketChannel.close(); serverSocketChannelServices.close(); embeddedJMS.stop(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println("IN shutdown Hook1"); /*try{ Thread.sleep(10000); } catch(Exception ex){ }*/ //webserverRequestProcessor.stop(); //webserverRequestProcessor1.stop(); /*warDeployer.stop(); executorService.stop(); //ataServer.stop(); //ataClient.stop(); messageServer.stop(); randomqueuemessagepicker.stop(); roundrobinqueuemessagepicker.stop(); topicpicker.stop();*/ /*try { mbs.invoke(new ObjectName("com.web.server:type=SARDeployer"), "destroyDeployer", null, null); } catch (InstanceNotFoundException | MalformedObjectNameException | ReflectionException | MBeanException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ //earDeployer.stop(); System.exit(0); }
From source file:gridool.communication.transport.nio.GridNioServer.java
private static Selector createSelector(int port) throws IOException { final Selector selector = SelectorProvider.provider().openSelector(); ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.configureBlocking(false); ServerSocket servSocket = serverChannel.socket(); servSocket.setReuseAddress(true);//www . j av a 2 s . c o m servSocket.bind(new InetSocketAddress(port)); serverChannel.register(selector, SelectionKey.OP_ACCEPT); if (LOG.isInfoEnabled()) { LOG.info("GridNioServer is started at port: " + port); } return selector; }
From source file:gridool.communication.transport.tcp.GridNioServer.java
private static void startListening(final Selector connectSelector, final int port) throws IOException { ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.configureBlocking(false); ServerSocket servSocket = serverChannel.socket(); servSocket.setReuseAddress(true);//from w w w . j av a 2 s .c o m servSocket.bind(new InetSocketAddress(port)); serverChannel.register(connectSelector, SelectionKey.OP_ACCEPT); if (LOG.isInfoEnabled()) { LOG.info("GridNioServer is started at port: " + port); } }
From source file:com.github.neoio.nio.util.NIOUtils.java
public static ServerSocketChannel openServerSocket(Selector selector, SocketAddress socketAddress) throws NetSocketException { ServerSocketChannel toReturn; try {/*w w w . j a va 2 s .c o m*/ toReturn = ServerSocketChannel.open(); toReturn.socket().bind(socketAddress); toReturn.configureBlocking(false); toReturn.register(selector, SelectionKey.OP_ACCEPT); } catch (IOException e) { logger.error("IOException occurred while opening server socket", e); toReturn = null; } return toReturn; }
From source file:com.l2jfree.network.mmocore.AcceptorThread.java
public void openServerSocket(InetAddress address, int port) throws IOException { ServerSocketChannel selectable = ServerSocketChannel.open(); selectable.configureBlocking(false); ServerSocket ss = selectable.socket(); ss.setReuseAddress(true);/* www.j a va 2 s . c o m*/ ss.setReceiveBufferSize(getBufferSize()); if (address == null) { ss.bind(new InetSocketAddress(port)); } else { ss.bind(new InetSocketAddress(address, port)); } selectable.register(getSelector(), SelectionKey.OP_ACCEPT); }
From source file:me.xingrz.prox.tcp.TcpProxy.java
@Override protected ServerSocketChannel createChannel(Selector selector) throws IOException { ServerSocketChannel channel = ServerSocketChannel.open(); channel.configureBlocking(false); channel.socket().bind(new InetSocketAddress(0)); channel.register(selector, SelectionKey.OP_ACCEPT, this); return channel; }
From source file:com.byteatebit.nbserver.simple.tcp.TcpConnectorFactory.java
@Override public IConnector create(ISelectorRegistrarBalancer selectorRegistrarBalancer, IComputeTaskScheduler taskScheduler, SocketAddress listenAddress) throws IOException { Preconditions.checkNotNull(selectorRegistrarBalancer, "selectorRegistrarBalancer cannot be null"); Preconditions.checkNotNull(taskScheduler, "taskScheduler cannot be null"); Preconditions.checkNotNull(listenAddress, "listenAddress cannot be null"); // open the server socketChannel ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); IOTimeoutTask timeoutTask = (selectionKey, ops) -> { LOG.error("selectionKey timeout"); selectionKey.cancel();//from w w w. java2 s .c o m IOUtils.closeQuietly(selectionKey.channel()); }; for (SocketOptionValue socketOptionValue : socketOptionValues) serverSocketChannel.setOption(socketOptionValue.getOption(), socketOptionValue.getValue()); SelectionKey serverSocketSelectionKey = selectorRegistrarBalancer.getSelectorRegistrar().register( serverSocketChannel, SelectionKey.OP_ACCEPT, selectionKey -> connectHandler.accept( new NbContext(selectorRegistrarBalancer.getSelectorRegistrar(), taskScheduler), selectionKey, serverSocketChannel), timeoutTask, -1); serverSocketChannel.socket().bind(listenAddress, maxServerSocketBacklog); return new TcpConnector(serverSocketSelectionKey, serverSocketChannel); }
From source file:org.sonews.daemon.sync.SynchronousNNTPDaemon.java
@Override public void run() { try {//from w w w . j av a 2 s . c o m Log.get().log(Level.INFO, "Server listening on port {0}", port); // Create a Selector that handles the SocketChannel multiplexing final Selector readSelector = Selector.open(); final Selector writeSelector = Selector.open(); // Start working threads final int workerThreads = Math.max(4, 2 * Runtime.getRuntime().availableProcessors()); ConnectionWorker[] cworkers = new ConnectionWorker[workerThreads]; for (int n = 0; n < workerThreads; n++) { cworkers[n] = new ConnectionWorker(); cworkers[n].start(); } Log.get().log(Level.INFO, "{0} worker threads started.", workerThreads); ChannelWriter.getInstance().setSelector(writeSelector); ChannelReader.getInstance().setSelector(readSelector); ChannelWriter.getInstance().start(); ChannelReader.getInstance().start(); final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(true); // Set to blocking mode // Configure ServerSocket; bind to socket... serverSocket = serverSocketChannel.socket(); serverSocket.bind(new InetSocketAddress(this.port)); while (isRunning()) { SocketChannel socketChannel; try { // As we set the server socket channel to blocking mode the // accept() // method will block. socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); assert socketChannel.isConnected(); assert socketChannel.finishConnect(); } catch (IOException ex) { // Under heavy load an IOException "Too many open files may // be thrown. It most cases we should slow down the // connection accepting, to give the worker threads some // time to process work. Log.get().log(Level.SEVERE, "IOException while accepting connection: {0}", ex.getMessage()); Log.get().info("Connection accepting sleeping for seconds..."); Thread.sleep(5000); // 5 seconds continue; } //FIXME conn should be NNTPConnection final SynchronousNNTPConnection conn = (SynchronousNNTPConnection) context .getBean("syncNNTPConnection", NNTPConnection.class); conn.setChannelWrapper(new SocketChannelWrapperFactory(socketChannel).create()); Connections.getInstance().add(conn); try { SelectionKey selKeyWrite = registerSelector(writeSelector, socketChannel, SelectionKey.OP_WRITE); registerSelector(readSelector, socketChannel, SelectionKey.OP_READ); Log.get().log(Level.INFO, "Connected: {0}", socketChannel.socket().getRemoteSocketAddress()); // Set write selection key and send hello to client conn.setWriteSelectionKey(selKeyWrite); conn.println("200 " + Config.inst().get(Config.HOSTNAME, "localhost") + " <unknown version>" // + Application.VERSION + " news server ready - (posting ok)."); } catch (CancelledKeyException cke) { Log.get().log(Level.WARNING, "CancelledKeyException {0} was thrown: {1}", new Object[] { cke.getMessage(), socketChannel.socket() }); } catch (ClosedChannelException cce) { Log.get().log(Level.WARNING, "ClosedChannelException {0} was thrown: {1}", new Object[] { cce.getMessage(), socketChannel.socket() }); } } } catch (BindException ex) { // Could not bind to socket; this is a fatal, so perform a shutdown Log.get().log(Level.SEVERE, ex.getLocalizedMessage() + " -> shutdown sonews", ex); setRunning(false); } catch (IOException ex) { ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:oz.hadoop.yarn.api.net.ApplicationContainerServerImpl.java
/** * //w w w . j a va 2s.com */ @Override void init() throws IOException { ServerSocketChannel channel = (ServerSocketChannel) this.rootChannel; channel.configureBlocking(false); channel.socket().bind(this.address); channel.register(this.selector, SelectionKey.OP_ACCEPT); if (logger.isInfoEnabled()) { logger.info("Bound to " + channel.getLocalAddress()); } }
From source file:org.reunionemu.jreunion.server.Network.java
public boolean register(InetSocketAddress address) { try {/* ww w . j a va2s .c o m*/ ServerSocketChannel serverChannel = ServerSocketChannel.open(); ServerSocket serverSocket = serverChannel.socket(); serverSocket.bind(address); serverChannel.configureBlocking(false); synchronized (this) { selector.wakeup(); serverChannel.register(selector, SelectionKey.OP_ACCEPT); } } catch (Exception e) { if (e instanceof BindException) { LoggerFactory.getLogger(Network.class) .error("Port " + address.getPort() + " not available. Is the server already running?", e); return false; } } return true; }