List of usage examples for java.nio.channels SocketChannel isConnected
public abstract boolean isConnected();
From source file:Main.java
public static void blockUntilConnected(final SocketChannel channel, long timeout) throws IOException { ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, timeout, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); FutureTask<Boolean> future = new FutureTask<Boolean>(new Callable<Boolean>() { public Boolean call() { while (!channel.isConnected()) { try { Thread.sleep(300); } catch (InterruptedException e) { }//from w w w.j av a 2 s .c o m } return true; } }); executor.execute(future); try { future.get(timeout, TimeUnit.MILLISECONDS); } catch (Exception e) { channel.close(); throw new IOException(e); } }
From source file:org.reunionemu.jreunion.server.Network.java
public void disconnect(SocketChannel socketChannel) { if (socketChannel.isConnected() && socketChannel.isOpen()) { processOutput(socketChannel);//ww w . j av a 2s .c om } LoggerFactory.getLogger(Network.class) .info("Disconnecting {local=" + socketChannel.socket().getLocalSocketAddress() + " remote=" + socketChannel.socket().getRemoteSocketAddress() + "}\n"); fireEvent(NetworkDisconnectEvent.class, socketChannel); try { socketChannel.close(); } catch (IOException e) { LoggerFactory.getLogger(this.getClass()).warn("Exception", e); } }
From source file:org.reunionemu.jreunion.server.Network.java
private boolean processOutput(SocketChannel socketChannel) { Client client = Server.getInstance().getWorld().getClients().get(socketChannel); if (client == null) return false; if (!socketChannel.isOpen() || !socketChannel.isConnected()) { disconnect(socketChannel);/*from w ww .j ava 2s .c o m*/ return false; } buffer.clear(); byte[] packetBytes = client.flush(); if (packetBytes == null) return true; buffer.put(packetBytes); buffer.flip(); try { socketChannel.write(buffer); } catch (IOException e) { LoggerFactory.getLogger(this.getClass()).error("Exception", e); disconnect(socketChannel); return false; } return true; }
From source file:org.sonews.daemon.sync.SynchronousNNTPDaemon.java
@Override public void run() { try {// w ww . j a va2s . c om 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:com.bittorrent.mpetazzoni.client.ConnectionHandler.java
/** * Return a human-readable representation of a connected socket channel. * * @param channel The socket channel to represent. * @return A textual representation (<em>host:port</em>) of the given * socket.//from ww w. j ava2s . c o m */ private String socketRepr(SocketChannel channel) { Socket s = channel.socket(); return String.format("%s:%d%s", s.getInetAddress().getHostName(), s.getPort(), channel.isConnected() ? "+" : "-"); }
From source file:morphy.service.SocketConnectionService.java
protected void disposeSocketChannel(SocketChannel channel) { if (channel.isConnected()) { try {/*from w w w . j a v a 2 s. c o m*/ channel.close(); } catch (Throwable t) { } } socketToSession.remove(channel.socket()); }
From source file:edu.hawaii.soest.pacioos.text.SocketTextSource.java
/** * A method used to the TCP socket of the remote source host for communication * @param host the name or IP address of the host to connect to for the * socket connection (reading) * @param portNumber the number of the TCP port to connect to (i.e. 2604) *//*from w w w . j a v a 2s.c o m*/ protected SocketChannel getSocketConnection() { String host = getHostName(); int portNumber = new Integer(getHostPort()).intValue(); SocketChannel dataSocket = null; try { // create the socket channel connection to the data source via the // converter serial2IP converter dataSocket = SocketChannel.open(); dataSocket.connect(new InetSocketAddress(host, portNumber)); // if the connection to the source fails, also disconnect from the RBNB // server and return null if (!dataSocket.isConnected()) { dataSocket.close(); disconnect(); dataSocket = null; } } catch (UnknownHostException ukhe) { log.info("Unable to look up host: " + host + "\n"); disconnect(); dataSocket = null; } catch (IOException nioe) { log.info("Couldn't get I/O connection to: " + host + ":" + portNumber); disconnect(); dataSocket = null; } return dataSocket; }
From source file:morphy.service.SocketConnectionService.java
private synchronized void onNewInput(SocketChannel channel) { if (!channel.isOpen()) return;/*from w w w . j a v a2 s . com*/ try { if (channel.isConnected()) { SocketChannelUserSession session = socketToSession.get(channel.socket()); if (session == null) { if (LOG.isErrorEnabled()) { LOG.error("Received a read on a socket not being managed. This is likely a bug."); } disposeSocketChannel(channel); } else { synchronized (session.getInputBuffer()) { String message = readMessage(channel); if (message != null && message.equals(MSG_TIMESEAL_OK)) { // Don't need to do anything. This was just the timeseal init string. } else if (message == null && channel.isOpen()) { session.disconnect(); } else if (message == null) { session.disconnect(); } else if (message.length() > 0) { /*if (!socketInputForCmd.containsKey(channel.socket())) { socketInputForCmd.put(channel.socket(), new StringBuilder()); } int c = (int)message.charAt(0); if (c != 10 && c != 13) { socketInputForCmd.get(channel.socket()).append(message); //LOG.info(c); } else { message = socketInputForCmd.get(channel.socket()).toString(); socketInputForCmd.put(channel.socket(), new StringBuilder()); LOG.info("Read: " + session.getUser().getUserName() + " \"" + message + "\""); } LOG.info(c + " " + socketInputForCmd.get(channel.socket()));*/ boolean expandAliases = true; if (message.startsWith("$$")) { message = message.substring(2); expandAliases = false; } else { session.touchLastReceivedTime(); session.getUser().getUserVars().getVariables().put("busy", ""); expandAliases = true; } session.getInputBuffer().append(message); if (session.getInputBuffer().indexOf("\n") != -1) { LOG.info("Read: " + session.getUser().getUserName() + " \"" + message + "\""); } int carrageReturnIndex = -1; while ((carrageReturnIndex = session.getInputBuffer().indexOf("\n")) != -1) { String command = session.getInputBuffer().substring(0, carrageReturnIndex).trim(); session.getInputBuffer().delete(0, carrageReturnIndex + 1); if (session .getCurrentState() == SocketChannelUserSession.UserSessionState.LOGIN_NEED_PASSWORD) { handlePasswordPromptText(session, command); } else if (command.equals("") || command.equals("\n") || command.equals("\n\r")) { session.send(""); } else if (session .getCurrentState() == SocketChannelUserSession.UserSessionState.LOGIN_NEED_USERNAME) { handleLoginPromptText(session, command); } else { if (expandAliases) { CommandService.getInstance().processCommandAndCheckAliases(command, session); } else { CommandService.getInstance().processCommand(command, session); } } } } } } } } catch (Throwable t) { if (LOG.isErrorEnabled()) { LOG.error("Error reading socket channel or processing command ", t); } } }
From source file:hornet.framework.clamav.service.ClamAVCheckService.java
/** * Ouverture de la socket./*from w w w . j a va 2 s .c o m*/ * * @return la socket * @throws ClamAVException * the clam av exception */ private SocketChannel openSocket() throws ClamAVException { SocketChannel channel = null; try { // Rcuperation de la socket depuis le pool channel = this.socketPool.borrowObject(); if (!channel.isOpen()) { channel = SocketChannel.open(); } if (!channel.isConnected()) { channel.configureBlocking(true); channel.connect(new InetSocketAddress(this.clamAVServer, this.clamAVPort)); } } catch (final Exception e) { ClamAVCheckService.LOGGER.error("Unable to borrow socket from pool", e); throw new ClamAVException(ERR_TEC_CLAMAV_01, new String[] { e.getMessage() }, e); } return channel; }
From source file:edu.hawaii.soest.kilonalu.ctd.SBE37Source.java
/** * A method used to the TCP socket of the remote source host for communication * @param host the name or IP address of the host to connect to for the * socket connection (reading) * @param portNumber the number of the TCP port to connect to (i.e. 2604) *//* w ww. ja v a 2s . com*/ protected SocketChannel getSocketConnection() { String host = getHostName(); int portNumber = new Integer(getHostPort()).intValue(); SocketChannel dataSocket = null; try { // create the socket channel connection to the data source via the // converter serial2IP converter dataSocket = SocketChannel.open(); //dataSocket.configureBlocking(false); dataSocket.connect(new InetSocketAddress(host, portNumber)); // if the connection to the source fails, also disconnect from the RBNB // server and return null if (!dataSocket.isConnected()) { dataSocket.close(); disconnect(); dataSocket = null; } } catch (UnknownHostException ukhe) { System.err.println("Unable to look up host: " + host + "\n"); disconnect(); dataSocket = null; } catch (IOException nioe) { System.err.println("Couldn't get I/O connection to: " + host); disconnect(); dataSocket = null; } catch (Exception e) { disconnect(); dataSocket = null; } return dataSocket; }