Java Code Examples for java.net.Socket.getChannel()

The following are Jave code examples for showing how to use getChannel() of the java.net.Socket class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: L2J-Global   File: MMOConnection.java   View Source Code Vote up 6 votes
public MMOConnection(SelectorThread<T> selectorThread, Socket socket, SelectionKey key, boolean tcpNoDelay)
{
	_selectorThread = selectorThread;
	_socket = socket;
	_address = socket.getInetAddress();
	_readableByteChannel = socket.getChannel();
	_writableByteChannel = socket.getChannel();
	_port = socket.getPort();
	_selectionKey = key;
	
	_sendQueue = new NioNetStackList<>();
	
	try
	{
		_socket.setTcpNoDelay(tcpNoDelay);
	}
	catch (SocketException e)
	{
		e.printStackTrace();
	}
}
 
Example 2
Project: monarch   File: ServerConnection.java   View Source Code Vote up 6 votes
public static ByteBuffer allocateCommBuffer(int size, Socket sock) {
  // I expect that size will almost always be the same value
  if (sock.getChannel() == null) {
    // The socket this commBuffer will be used for is old IO (it has no channel).
    // So the commBuffer should be heap based.
    return ByteBuffer.allocate(size);
  }
  LinkedBlockingQueue<ByteBuffer> q = commBufferMap.get(size);
  ByteBuffer result = null;
  if (q != null) {
    result = q.poll();
  }
  if (result == null) {
    result = ByteBuffer.allocateDirect(size);
  } else {
    result.position(0);
    result.limit(result.capacity());
  }
  return result;
}
 
Example 3
Project: openjdk-jdk10   File: SocketOrChannelConnectionImpl.java   View Source Code Vote up 5 votes
public SocketOrChannelConnectionImpl(ORB orb,
                                     Acceptor acceptor,
                                     Socket socket)
{
    this(orb, acceptor, socket,
         (socket.getChannel() == null
          ? false
          : orb.getORBData().connectionSocketUseSelectThreadToWait()),
         (socket.getChannel() == null
          ? false
          : orb.getORBData().connectionSocketUseWorkerThreadForEvent()));
}
 
Example 4
Project: openjdk-jdk10   File: SocketOrChannelConnectionImpl.java   View Source Code Vote up 5 votes
public SocketOrChannelConnectionImpl(ORB orb,
                                     Acceptor acceptor,
                                     Socket socket,
                                     boolean useSelectThreadToWait,
                                     boolean useWorkerThread)
{
    this(orb, useSelectThreadToWait, useWorkerThread);

    this.socket = socket;
    socketChannel = socket.getChannel();
    if (socketChannel != null) {
        // REVISIT
        try {
            boolean isBlocking = !useSelectThreadToWait;
            socketChannel.configureBlocking(isBlocking);
        } catch (IOException e) {
            RuntimeException rte = new RuntimeException();
            rte.initCause(e);
            throw rte;
        }
    }
    this.acceptor = acceptor;

    serverRequestMap = Collections.synchronizedMap(new HashMap());
    isServer = true;

    state = ESTABLISHED;
}
 
Example 5
Project: hadoop-oss   File: SocketInputWrapper.java   View Source Code Vote up 5 votes
SocketInputWrapper(Socket s, InputStream is) {
  super(is);
  this.socket = s;
  this.hasChannel = s.getChannel() != null;
  if (hasChannel) {
    Preconditions.checkArgument(is instanceof SocketInputStream,
        "Expected a SocketInputStream when there is a channel. " +
        "Got: %s", is);
  }
}
 
Example 6
Project: OpenJSharp   File: SocketOrChannelConnectionImpl.java   View Source Code Vote up 5 votes
public SocketOrChannelConnectionImpl(ORB orb,
                                     Acceptor acceptor,
                                     Socket socket,
                                     boolean useSelectThreadToWait,
                                     boolean useWorkerThread)
{
    this(orb, useSelectThreadToWait, useWorkerThread);

    this.socket = socket;
    socketChannel = socket.getChannel();
    if (socketChannel != null) {
        // REVISIT
        try {
            boolean isBlocking = !useSelectThreadToWait;
            socketChannel.configureBlocking(isBlocking);
        } catch (IOException e) {
            RuntimeException rte = new RuntimeException();
            rte.initCause(e);
            throw rte;
        }
    }
    this.acceptor = acceptor;

    serverRequestMap = Collections.synchronizedMap(new HashMap());
    isServer = true;

    state = ESTABLISHED;
}
 
Example 7
Project: OpenJSharp   File: SocketOrChannelConnectionImpl.java   View Source Code Vote up 5 votes
public SocketOrChannelConnectionImpl(ORB orb,
                                     Acceptor acceptor,
                                     Socket socket)
{
    this(orb, acceptor, socket,
         (socket.getChannel() == null
          ? false
          : orb.getORBData().connectionSocketUseSelectThreadToWait()),
         (socket.getChannel() == null
          ? false
          : orb.getORBData().connectionSocketUseWorkerThreadForEvent()));
}
 
Example 8
Project: hadoop   File: TcpPeerServer.java   View Source Code Vote up 5 votes
public static Peer peerFromSocket(Socket socket)
    throws IOException {
  Peer peer = null;
  boolean success = false;
  try {
    // TCP_NODELAY is crucial here because of bad interactions between
    // Nagle's Algorithm and Delayed ACKs. With connection keepalive
    // between the client and DN, the conversation looks like:
    //   1. Client -> DN: Read block X
    //   2. DN -> Client: data for block X
    //   3. Client -> DN: Status OK (successful read)
    //   4. Client -> DN: Read block Y
    // The fact that step #3 and #4 are both in the client->DN direction
    // triggers Nagling. If the DN is using delayed ACKs, this results
    // in a delay of 40ms or more.
    //
    // TCP_NODELAY disables nagling and thus avoids this performance
    // disaster.
    socket.setTcpNoDelay(true);
    SocketChannel channel = socket.getChannel();
    if (channel == null) {
      peer = new BasicInetPeer(socket);
    } else {
      peer = new NioInetPeer(socket);
    }
    success = true;
    return peer;
  } finally {
    if (!success) {
      if (peer != null) peer.close();
      socket.close();
    }
  }
}
 
Example 9
Project: monarch   File: ChunkedStreamMessage.java   View Source Code Vote up 5 votes
@Override
public void setComms(Socket socket, InputStream is, OutputStream os, ByteBuffer bb,
    MessageStats msgStats) throws IOException {
  Assert.assertTrue(socket != null);
  this.socket = socket;
  this.sockCh = socket.getChannel();
  this.is = is;
  this.os = new BufferedOutputStream(os);
  this.cachedCommBuffer = bb;
  this.msgStats = msgStats;
}
 
Example 10
Project: incubator-netbeans   File: ShellAgent.java   View Source Code Vote up 4 votes
/**
     * Creates a new Connection using the agent. Throws an IOException if the
     * connection attempt is not successful or times out. If an old connection is
     * still open, it is closed and event is fired.
     * 
     * @return the Connection the new connection
     * @throws IOException 
     */
    @NbBundle.Messages(value = {
        "MSG_AgentConnectionBroken=Control connection with JShell VM is broken, could not connect to agent",
        "MSG_AgentNotReady=The JShell VM is not ready for operation"
    })
    public JShellConnection createConnection() throws IOException {
        JShellConnection old;
        synchronized (this) {
            if (closed) {
                throw new IOException(Bundle.MSG_AgentConnectionBroken());
            }
            if (expectDebugger && debuggerMachine == null) {
                return null;
            }
//            old = connection;
//            connection = null;
        }
        /*
        if (old != null) {
            old.shutDown();
            // notify about the old connection being trashed
            ShellLaunchEvent ev = new ShellLaunchEvent(mgr, old, false);
            mgr.fire((l) -> l.connectionClosed(ev));
        }
        */
        SocketChannel sc = SocketChannel.open();
        sc.configureBlocking(true);
        Socket sock = sc.socket();
        sock.connect(connectAddress, ShellLaunchManager.CONNECT_TIMEOUT);
        // turn to nonblocking mode
        sc.configureBlocking(false);
        boolean notify = false;
        JShellConnection con = new JShellConnection(this, sock.getChannel());
        /*
        synchronized (this) {
            if (connection == null) {
                connection = con;
                notify = true;
            } else {
                con = connection;
            }
        }
        */
        synchronized (this) {
            connections.add(con);
        }
        if (notify) {
            ShellLaunchEvent ev = new ShellLaunchEvent(mgr, con, false);
            mgr.fire((l) -> l.connectionInitiated(ev));
        }
        return con;
    }
 
Example 11
Project: hadoop-oss   File: NetUtils.java   View Source Code Vote up 4 votes
/**
 * Like {@link NetUtils#connect(Socket, SocketAddress, int)} but
 * also takes a local address and port to bind the socket to. 
 * 
 * @param socket
 * @param endpoint the remote address
 * @param localAddr the local address to bind the socket to
 * @param timeout timeout in milliseconds
 */
public static void connect(Socket socket, 
                           SocketAddress endpoint,
                           SocketAddress localAddr,
                           int timeout) throws IOException {
  if (socket == null || endpoint == null || timeout < 0) {
    throw new IllegalArgumentException("Illegal argument for connect()");
  }
  
  SocketChannel ch = socket.getChannel();
  
  if (localAddr != null) {
    Class localClass = localAddr.getClass();
    Class remoteClass = endpoint.getClass();
    Preconditions.checkArgument(localClass.equals(remoteClass),
        "Local address %s must be of same family as remote address %s.",
        localAddr, endpoint);
    socket.bind(localAddr);
  }

  try {
    if (ch == null) {
      // let the default implementation handle it.
      socket.connect(endpoint, timeout);
    } else {
      SocketIOWithTimeout.connect(ch, endpoint, timeout);
    }
  } catch (SocketTimeoutException ste) {
    throw new ConnectTimeoutException(ste.getMessage());
  }

  // There is a very rare case allowed by the TCP specification, such that
  // if we are trying to connect to an endpoint on the local machine,
  // and we end up choosing an ephemeral port equal to the destination port,
  // we will actually end up getting connected to ourself (ie any data we
  // send just comes right back). This is only possible if the target
  // daemon is down, so we'll treat it like connection refused.
  if (socket.getLocalPort() == socket.getPort() &&
      socket.getLocalAddress().equals(socket.getInetAddress())) {
    LOG.info("Detected a loopback TCP socket, disconnecting it");
    socket.close();
    throw new ConnectException(
      "Localhost targeted connection resulted in a loopback. " +
      "No daemon is listening on the target port.");
  }
}
 
Example 12
Project: hadoop-oss   File: NetUtils.java   View Source Code Vote up 3 votes
/**
 * Return a {@link SocketInputWrapper} for the socket and set the given
 * timeout. If the socket does not have an associated channel, then its socket
 * timeout will be set to the specified value. Otherwise, a
 * {@link SocketInputStream} will be created which reads with the configured
 * timeout.
 * 
 * Any socket created using socket factories returned by {@link #NetUtils},
 * must use this interface instead of {@link Socket#getInputStream()}.
 * 
 * In general, this should be called only once on each socket: see the note
 * in {@link SocketInputWrapper#setTimeout(long)} for more information.
 *
 * @see Socket#getChannel()
 * 
 * @param socket
 * @param timeout timeout in milliseconds. zero for waiting as
 *                long as necessary.
 * @return SocketInputWrapper for reading from the socket.
 * @throws IOException
 */
public static SocketInputWrapper getInputStream(Socket socket, long timeout) 
                                         throws IOException {
  InputStream stm = (socket.getChannel() == null) ? 
        socket.getInputStream() : new SocketInputStream(socket);
  SocketInputWrapper w = new SocketInputWrapper(socket, stm);
  w.setTimeout(timeout);
  return w;
}
 
Example 13
Project: hadoop   File: NetUtils.java   View Source Code Vote up 3 votes
/**
 * Return a {@link SocketInputWrapper} for the socket and set the given
 * timeout. If the socket does not have an associated channel, then its socket
 * timeout will be set to the specified value. Otherwise, a
 * {@link SocketInputStream} will be created which reads with the configured
 * timeout.
 * 
 * Any socket created using socket factories returned by {@link #NetUtils},
 * must use this interface instead of {@link Socket#getInputStream()}.
 * 
 * In general, this should be called only once on each socket: see the note
 * in {@link SocketInputWrapper#setTimeout(long)} for more information.
 *
 * @see Socket#getChannel()
 * 
 * @param socket
 * @param timeout timeout in milliseconds. zero for waiting as
 *                long as necessary.
 * @return SocketInputWrapper for reading from the socket.
 * @throws IOException
 */
public static SocketInputWrapper getInputStream(Socket socket, long timeout) 
                                         throws IOException {
  InputStream stm = (socket.getChannel() == null) ? 
        socket.getInputStream() : new SocketInputStream(socket);
  SocketInputWrapper w = new SocketInputWrapper(socket, stm);
  w.setTimeout(timeout);
  return w;
}
 
Example 14
Project: hadoop-oss   File: SocketOutputStream.java   View Source Code Vote up 2 votes
/**
 * Same as SocketOutputStream(socket.getChannel(), timeout):<br><br>
 * 
 * Create a new ouput stream with the given timeout. If the timeout
 * is zero, it will be treated as infinite timeout. The socket's
 * channel will be configured to be non-blocking.
 * 
 * @see SocketOutputStream#SocketOutputStream(WritableByteChannel, long)
 *  
 * @param socket should have a channel associated with it.
 * @param timeout timeout timeout in milliseconds. must not be negative.
 * @throws IOException
 */
public SocketOutputStream(Socket socket, long timeout) 
                                       throws IOException {
  this(socket.getChannel(), timeout);
}
 
Example 15
Project: hadoop-oss   File: SocketInputStream.java   View Source Code Vote up 2 votes
/**
 * Same as SocketInputStream(socket.getChannel(), timeout): <br><br>
 * 
 * Create a new input stream with the given timeout. If the timeout
 * is zero, it will be treated as infinite timeout. The socket's
 * channel will be configured to be non-blocking.
 * 
 * @see SocketInputStream#SocketInputStream(ReadableByteChannel, long)
 *  
 * @param socket should have a channel associated with it.
 * @param timeout timeout timeout in milliseconds. must not be negative.
 * @throws IOException
 */
public SocketInputStream(Socket socket, long timeout) 
                                       throws IOException {
  this(socket.getChannel(), timeout);
}
 
Example 16
Project: hadoop   File: SocketInputStream.java   View Source Code Vote up 2 votes
/**
 * Same as SocketInputStream(socket.getChannel(), timeout): <br><br>
 * 
 * Create a new input stream with the given timeout. If the timeout
 * is zero, it will be treated as infinite timeout. The socket's
 * channel will be configured to be non-blocking.
 * 
 * @see SocketInputStream#SocketInputStream(ReadableByteChannel, long)
 *  
 * @param socket should have a channel associated with it.
 * @param timeout timeout timeout in milliseconds. must not be negative.
 * @throws IOException
 */
public SocketInputStream(Socket socket, long timeout) 
                                       throws IOException {
  this(socket.getChannel(), timeout);
}
 
Example 17
Project: spark_deep   File: SocketOutputStream.java   View Source Code Vote up 2 votes
/**
 * Same as SocketOutputStream(socket.getChannel(), timeout):<br><br>
 * 
 * Create a new ouput stream with the given timeout. If the timeout
 * is zero, it will be treated as infinite timeout. The socket's
 * channel will be configured to be non-blocking.
 * 
 * @see SocketOutputStream#SocketOutputStream(WritableByteChannel, long)
 *  
 * @param socket should have a channel associated with it.
 * @param timeout timeout timeout in milliseconds. must not be negative.
 * @throws IOException
 */
public SocketOutputStream(Socket socket, long timeout) 
                                       throws IOException {
  this(socket.getChannel(), timeout);
}
 
Example 18
Project: hadoop   File: SocketOutputStream.java   View Source Code Vote up 2 votes
/**
 * Same as SocketOutputStream(socket.getChannel(), timeout):<br><br>
 * 
 * Create a new ouput stream with the given timeout. If the timeout
 * is zero, it will be treated as infinite timeout. The socket's
 * channel will be configured to be non-blocking.
 * 
 * @see SocketOutputStream#SocketOutputStream(WritableByteChannel, long)
 *  
 * @param socket should have a channel associated with it.
 * @param timeout timeout timeout in milliseconds. must not be negative.
 * @throws IOException
 */
public SocketOutputStream(Socket socket, long timeout) 
                                       throws IOException {
  this(socket.getChannel(), timeout);
}
 
Example 19
Project: spark_deep   File: SocketInputStream.java   View Source Code Vote up 2 votes
/**
 * Same as SocketInputStream(socket.getChannel(), socket.getSoTimeout())
 * :<br><br>
 * 
 * Create a new input stream with the given timeout. If the timeout
 * is zero, it will be treated as infinite timeout. The socket's
 * channel will be configured to be non-blocking.
 * @see SocketInputStream#SocketInputStream(ReadableByteChannel, long)
 *  
 * @param socket should have a channel associated with it.
 * @throws IOException
 */
public SocketInputStream(Socket socket) throws IOException {
  this(socket.getChannel(), socket.getSoTimeout());
}
 
Example 20
Project: hadoop   File: NetUtils.java   View Source Code Vote up 2 votes
/**
 * Returns OutputStream for the socket. If the socket has an associated
 * SocketChannel then it returns a 
 * {@link SocketOutputStream} with the given timeout. If the socket does not
 * have a channel, {@link Socket#getOutputStream()} is returned. In the later
 * case, the timeout argument is ignored and the write will wait until 
 * data is available.<br><br>
 * 
 * Any socket created using socket factories returned by {@link NetUtils},
 * must use this interface instead of {@link Socket#getOutputStream()}.
 * 
 * @see Socket#getChannel()
 * 
 * @param socket
 * @param timeout timeout in milliseconds. This may not always apply. zero
 *        for waiting as long as necessary.
 * @return OutputStream for writing to the socket.
 * @throws IOException   
 */
public static OutputStream getOutputStream(Socket socket, long timeout) 
                                           throws IOException {
  return (socket.getChannel() == null) ? 
          socket.getOutputStream() : new SocketOutputStream(socket, timeout);            
}