Example usage for java.nio.channels SocketChannel socket

List of usage examples for java.nio.channels SocketChannel socket

Introduction

In this page you can find the example usage for java.nio.channels SocketChannel socket.

Prototype

public abstract Socket socket();

Source Link

Document

Retrieves a socket associated with this channel.

Usage

From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java

private TcpConnectionSupport mockedTcpNioConnection() throws Exception {
    SocketChannel socketChannel = mock(SocketChannel.class);
    new DirectFieldAccessor(socketChannel).setPropertyValue("open", false);
    doThrow(new IOException("Foo")).when(socketChannel).write(Mockito.any(ByteBuffer.class));
    when(socketChannel.socket()).thenReturn(mock(Socket.class));
    TcpNioConnection conn = new TcpNioConnection(socketChannel, false, false, new ApplicationEventPublisher() {

        @Override//from   ww  w  .  jav  a2s .com
        public void publishEvent(ApplicationEvent event) {
        }

        @Override
        public void publishEvent(Object event) {

        }

    }, "foo");
    conn.setMapper(new TcpMessageMapper());
    conn.setSerializer(new ByteArrayCrLfSerializer());
    return conn;
}

From source file:org.cloudata.core.commitlog.CommitLogClient.java

private TransactionData[] readDataFrom(Method readMethod, int index, String tabletName) throws IOException {
    int port = -1;
    int replicaCount = rpcUtil.getMultiRpcCount();

    for (int count = 0; count < replicaCount; count++) {
        try {//from  ww  w .ja  v a  2  s .c o m
            port = (Integer) rpcUtil.singleCall(readMethod, index, tabletName);
            if (port > 0) {
                break;
            }
        } catch (IOException e) {
            LOG.info("Exception in reading commit log data : " + e);
        }

        if (++index % replicaCount == 0) {
            index = 0;
        }
    }

    if (port < 0) {
        return null;
    }

    SocketChannel socketChannel = SocketChannel.open();
    List<TransactionData> txDataList = null;
    try {
        socketChannel.connect(new InetSocketAddress(rpcUtil.getAddressAt(index), port));
        DataInputStream dis = new DataInputStream(
                new BufferedInputStream(socketChannel.socket().getInputStream(), 8192));

        txDataList = readTxDataFrom(tabletName, dis);
    } finally {
        socketChannel.socket().close();
        socketChannel.close();
    }

    return txDataList.toArray(new TransactionData[0]);
}

From source file:org.apache.hadoop.mapred.buffer.Manager.java

public void open() throws IOException {
    Configuration conf = tracker.conf();
    int maxMaps = conf.getInt("mapred.tasktracker.map.tasks.maximum", 2);
    int maxReduces = conf.getInt("mapred.tasktracker.reduce.tasks.maximum", 1);

    InetSocketAddress serverAddress = getServerAddress(conf);
    this.server = RPC.getServer(this, serverAddress.getHostName(), serverAddress.getPort(),
            maxMaps + maxReduces, false, conf);
    this.server.start();

    this.requestTransfer.setPriority(Thread.MAX_PRIORITY);
    this.requestTransfer.start();

    /** The server socket and selector registration */
    InetSocketAddress controlAddress = getControlAddress(conf);
    this.controlPort = controlAddress.getPort();
    this.channel = ServerSocketChannel.open();
    this.channel.socket().bind(controlAddress);

    this.acceptor = new Thread() {
        @Override//from   ww w. java 2 s  .  c  om
        public void run() {
            while (!isInterrupted()) {
                SocketChannel connection = null;
                try {
                    connection = channel.accept();
                    DataInputStream in = new DataInputStream(connection.socket().getInputStream());
                    int numRequests = in.readInt();
                    for (int i = 0; i < numRequests; i++) {
                        BufferRequest request = BufferRequest.read(in);
                        if (request instanceof ReduceBufferRequest) {
                            add((ReduceBufferRequest) request);
                            LOG.info("add new request " + request);
                        } else if (request instanceof MapBufferRequest) {
                            add((MapBufferRequest) request);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (connection != null)
                            connection.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    };
    this.acceptor.setDaemon(true);
    this.acceptor.setPriority(Thread.MAX_PRIORITY);
    this.acceptor.start();

    this.serviceQueue = new Thread() {
        public void run() {
            List<OutputFile> service = new ArrayList<OutputFile>();
            while (!isInterrupted()) {
                try {
                    OutputFile o = queue.take();
                    service.add(o);
                    queue.drainTo(service);
                    for (OutputFile file : service) {
                        try {
                            if (file != null)
                                add(file);
                        } catch (Throwable t) {
                            t.printStackTrace();
                            LOG.error("Error service file: " + file + ". " + t);
                        }
                    }
                } catch (Throwable t) {
                    t.printStackTrace();
                    LOG.error(t);
                } finally {
                    service.clear();
                }
            }
            LOG.info("Service queue thread exit.");
        }
    };
    this.serviceQueue.setPriority(Thread.MAX_PRIORITY);
    this.serviceQueue.setDaemon(true);
    this.serviceQueue.start();
}

From source file:edu.hawaii.soest.kilonalu.tchain.TChainSource.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.  j a v a 2 s .co 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();
        Socket tcpSocket = dataSocket.socket();
        tcpSocket.setTcpNoDelay(true);
        tcpSocket.setReceiveBufferSize(40);
        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;

}

From source file:com.springrts.springls.Client.java

public Client(SocketChannel sockChan) {

    this.alive = true;

    // no info on user/pass, zero access
    this.account = new Account();
    this.sockChan = sockChan;
    this.ip = sockChan.socket().getInetAddress();
    // this fixes the issue with local user connecting to the server at
    // "127.0.0.1", as he can not host battles with that ip
    if (ip.isLoopbackAddress()) {
        InetAddress newIP = Misc.getLocalIpAddress();
        if (newIP != null) {
            ip = newIP;/*from  ww w.j  a  va2  s.c  o  m*/
        } else {
            LOG.warn("Could not resolve local IP address."
                    + " The user may have problems with hosting battles.");
        }
    }
    localIp = ip; // will be changed later once the client logs in
    udpSourcePort = 0; // yet unknown
    selKey = null;
    recvBuf = new StringBuilder();
    inGame = false;
    away = false;
    locale = ProtocolUtil.countryToLocale(ProtocolUtil.COUNTRY_UNKNOWN);
    inGameTime = 0;
    battleID = Battle.NO_BATTLE_ID;
    requestedBattleID = Battle.NO_BATTLE_ID;
    cpu = 0;
    scriptPassword = NO_SCRIPT_PASSWORD;
    scriptPasswordSupported = false;
    compatFlags = new ArrayList<String>(0);

    timeOfLastReceive = System.currentTimeMillis();
}

From source file:com.sun.grizzly.http.jk.common.ChannelNioSocket.java

public void accept(MsgContext ep) throws IOException {
    if (sSocket == null) {
        return;/*from w  w  w .ja  va 2  s .  c om*/
    }
    synchronized (this) {
        while (paused) {
            try {
                wait();
            } catch (InterruptedException ie) {
                //Ignore, since can't happen
            }
        }
    }
    SocketChannel sc = sSocket.getChannel().accept();
    Socket s = sc.socket();
    ep.setNote(socketNote, s);
    if (LoggerUtils.getLogger().isLoggable(Level.FINEST)) {
        LoggerUtils.getLogger().log(Level.FINEST, "Accepted socket " + s + " channel " + sc.isBlocking());
    }

    try {
        setSocketOptions(s);
    } catch (SocketException sex) {
        LoggerUtils.getLogger().log(Level.FINEST, "Error initializing Socket Options", sex);
    }

    requestCount++;

    sc.configureBlocking(false);
    InputStream is = new SocketInputStream(sc);
    OutputStream os = new SocketOutputStream(sc);
    ep.setNote(isNote, is);
    ep.setNote(osNote, os);
    ep.setControl(tp);
}

From source file:ca.wumbo.doommanager.server.ServerManager.java

/**
 * Attempts to accept incoming new connections.
 * //  w ww. java  2  s  .  co  m
 * @return
 *       True if there was no error, false if an error occured.
 */
private boolean acceptConnections() {
    SocketChannel socketChannel = null;

    // Only bother if the connection is open.
    if (serverSocketChannel.isOpen()) {

        // Attempt to get a connection.
        try {
            socketChannel = serverSocketChannel.accept();
        } catch (Exception e) {
            log.error("Unexpected IO exception when accepting a connection.", e);
            return false;
        }

        // If there was a client connecting, take care of them.
        // Make sure to attach a new ClientInfo that we will fill out later upon validation.
        if (socketChannel != null) {
            try {
                log.info("Incoming new client connection from {}.",
                        socketChannel.getRemoteAddress().toString());
                ClientInfo clientInfo = new ClientInfo(socketChannel.getRemoteAddress().toString());
                socketChannel.configureBlocking(false);
                socketChannel.socket().setTcpNoDelay(true);
                socketChannel.register(selector, SelectionKey.OP_READ, clientInfo);
                clientInfo.markMessageReceived(); // Prevent timing out from a connection.

                //               // TEST
                //               int amount = 1024 * 16;
                //               byte[] hi = new byte[amount];
                //               for (int i = 0; i < amount; i++)
                //                  hi[i] = (byte)(Math.random() * 255);
                //               ByteBuffer bb = ByteBuffer.allocate(amount);
                //               bb.put(hi);
                //               bb.flip();
                //               
                //               int wrote = 0;
                //               while (bb.hasRemaining()) {
                //                  wrote = socketChannel.write(bb);
                //                  System.out.println("Server wrote: " + wrote + " bytes to a client");
                //               }
                //               
                //               Thread.sleep(4000);
                //               
                //               bb = ByteBuffer.allocate(5);
                //               bb.put(new byte[] { 1, 2, 3, 4, 5 });
                //               bb.flip();
                //               wrote = 0;
                //               while (bb.hasRemaining()) {
                //                  wrote = socketChannel.write(bb);
                //                  System.out.println("2) Server wrote: " + wrote + " bytes to a client");
                //               }

                // TODO - send global version of the file.
            } catch (ClosedChannelException e) {
                log.error("Channel closed exception when registering a connected client.", e);
                return false;
            } catch (IOException e) {
                log.error("IO exception when registering a new client connection.", e);
                return false;
            } catch (Exception e) {
                log.error("Unexpected exception when registering a new client connection.", e);
                return false;
            }
        }
    }

    // Signal all is good.
    return true;
}

From source file:morphy.service.SocketConnectionService.java

protected synchronized String readMessage(SocketChannel channel) {
    try {//from ww w .  ja v a2s . c  o m
        ByteBuffer buffer = ByteBuffer.allocate(maxCommunicationSizeBytes);
        int charsRead = -1;
        try {
            charsRead = channel.read(buffer);
        } catch (IOException cce) {
            if (channel.isOpen()) {
                channel.close();
                if (LOG.isInfoEnabled()) {
                    LOG.info("Closed channel " + channel);
                }
            }
        }
        if (charsRead == -1) {
            return null;
        } else if (charsRead > 0) {
            buffer.flip();

            Charset charset = Charset.forName(Morphy.getInstance().getMorphyPreferences()
                    .getString(PreferenceKeys.SocketConnectionServiceCharEncoding));

            SocketChannelUserSession socketChannelUserSession = socketToSession.get(channel.socket());

            byte[] bytes = buffer.array();
            buffer.position(0);

            System.out.println("IN: " + new String(bytes).trim());
            if (looksLikeTimesealInit(bytes)) {
                if (socketChannelUserSession.usingTimeseal == false) {
                    // First time?
                    socketChannelUserSession.usingTimeseal = true;
                    return MSG_TIMESEAL_OK;
                }
            }

            if (socketChannelUserSession.usingTimeseal) {
                /*
                 * Clients may pass multiple Timeseal-encoded messages at once.
                 * We need to parse each separated message to Timeseal decoder as necessary. 
                 */

                byte[] bytesToDecode = Arrays.copyOfRange(bytes, 0, charsRead - 1 /* \n or 10 */);
                byte[][] splitBytes = TimesealCoder.splitBytes(bytesToDecode, (byte) 10);

                buffer = ByteBuffer.allocate(bytesToDecode.length);
                buffer.position(0);
                for (int i = 0; i < splitBytes.length; i++) {
                    byte[] splitBytesToDecode = splitBytes[i];
                    TimesealParseResult parseResult = timesealCoder.decode(splitBytesToDecode);
                    if (parseResult != null) {
                        System.out.println(parseResult.getTimestamp());
                        parseResult.setMessage(parseResult.getMessage() + "\n");
                        System.out.println(parseResult.getMessage());

                        buffer.put(parseResult.getMessage().getBytes(charset));
                    }
                }
                //buffer.position(0);
                buffer.flip();
            }

            CharsetDecoder decoder = charset.newDecoder();
            CharBuffer charBuffer = decoder.decode(buffer);
            String message = charBuffer.toString();
            return message;
            //System.out.println(message);
            //return "";
        } else {
            return "";
        }
    } catch (Throwable t) {
        if (LOG.isErrorEnabled())
            LOG.error("Error reading SocketChannel " + channel.socket().getLocalAddress(), t);
        return null;
    }
}

From source file:org.sonews.daemon.sync.SynchronousNNTPDaemon.java

@Override
public void run() {
    try {/*from w w w  .  ja  v  a 2s  .  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:org.gcaldaemon.core.ldap.LDAPListener.java

public final void run() {
    log.info("LDAP server started successfully.");

    // Create variables
    SelectionKey key, newKey;//  ww  w .  j  av  a2s.  c o  m
    SocketChannel channel;
    Socket socket = null;
    Iterator keys;
    int n;

    // Server loop
    for (;;) {
        try {

            // Select sockets
            try {
                socket = null;
                n = selector.select();
            } catch (NullPointerException closedError) {

                // Ignore Selector bug - client socket closed
                if (log.isDebugEnabled()) {
                    log.debug("Socket closed.", closedError);
                }
                continue;
            } catch (ClosedSelectorException interrupt) {
                break;
            } catch (Exception selectError) {

                // Unknown exception - stop server
                log.warn("Unable to select sockets!", selectError);
                break;
            }

            if (n != 0) {

                // Get an iterator over the set of selected keys
                keys = selector.selectedKeys().iterator();
                if (keys == null) {
                    continue;
                }

                // Look at each key in the selected set
                while (keys.hasNext()) {
                    key = (SelectionKey) keys.next();
                    keys.remove();

                    // Nothing to do
                    if (key == null) {
                        continue;
                    }

                    // Check key status
                    if (key.isValid()) {

                        // Accept new incoming connection
                        if (key.isAcceptable()) {
                            channel = serverChannel.accept();
                            if (channel != null) {

                                // Register new socket connection
                                socket = channel.socket();
                                channel.configureBlocking(false);
                                newKey = channel.register(selector, SelectionKey.OP_READ);
                                processAccept(newKey);
                            }
                        } else {
                            if (key.isReadable()) {

                                // Read from socket connection
                                socket = ((SocketChannel) key.channel()).socket();
                                processRead(key);
                            } else {

                                // Write to socket connection
                                if (key.isWritable()) {
                                    socket = ((SocketChannel) key.channel()).socket();
                                    processWrite(key);
                                }
                            }
                        }
                    }
                }
            }
        } catch (InterruptedException interrupt) {
            closeSocket(socket);
            break;
        } catch (IOException socketClosed) {
            closeSocket(socket);
            continue;
        } catch (Exception processingException) {
            closeSocket(socket);
            log.warn(processingException.getMessage(), processingException);
        }
    }
    log.info("LDAP server stopped.");
}