Java Code Examples for java.nio.channels.SocketChannel#socket()

The following examples show how to use java.nio.channels.SocketChannel#socket() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SSLSocketChannel.java    From nifi with Apache License 2.0 6 votes vote down vote up
public SSLSocketChannel(final SSLContext sslContext, final SocketChannel socketChannel, final boolean client) throws IOException {
    if (!socketChannel.isConnected()) {
        throw new IllegalArgumentException("Cannot pass an un-connected SocketChannel");
    }

    this.channel = socketChannel;

    this.socketAddress = socketChannel.getRemoteAddress();
    final Socket socket = socketChannel.socket();
    this.hostname = socket.getInetAddress().getHostName();
    this.port = socket.getPort();

    this.engine = sslContext.createSSLEngine();
    this.engine.setUseClientMode(client);
    this.engine.setNeedClientAuth(true);

    streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
    streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
    appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()));
}
 
Example 2
Source File: Selector.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Register the nioSelector with an existing channel
 * Use this on server-side, when a connection is accepted by a different thread but processed by the Selector
 * Note that we are not checking if the connection id is valid - since the connection already exists
 */
public String register(SocketChannel channel, PortType portType) throws IOException {
  Socket socket = channel.socket();
  String connectionId = generateConnectionId(channel);
  SelectionKey key = channel.register(nioSelector, SelectionKey.OP_READ);
  Transmission transmission;
  try {
    transmission =
        createTransmission(connectionId, key, socket.getInetAddress().getHostName(), socket.getPort(), portType,
            SSLFactory.Mode.SERVER);
  } catch (IOException e) {
    logger.error("IOException on transmission creation ", e);
    socket.close();
    channel.close();
    throw e;
  }
  key.attach(transmission);
  this.keyMap.put(connectionId, key);
  numActiveConnections.set(this.keyMap.size());
  return connectionId;
}
 
Example 3
Source File: SSLSocketChannel.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public SSLSocketChannel(final SSLEngine sslEngine, final SocketChannel socketChannel) throws IOException {
    if (!socketChannel.isConnected()) {
        throw new IllegalArgumentException("Cannot pass an un-connected SocketChannel");
    }

    this.channel = socketChannel;

    this.socketAddress = socketChannel.getRemoteAddress();
    final Socket socket = socketChannel.socket();
    this.hostname = socket.getInetAddress().getHostName();
    this.port = socket.getPort();

    // don't set useClientMode or needClientAuth, use the engine as is and let the caller configure it
    this.engine = sslEngine;

    streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
    streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
    appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()));
}
 
Example 4
Source File: TcpConnection.java    From kryonet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public SelectionKey accept (Selector selector, SocketChannel socketChannel) throws IOException {
	writeBuffer.clear();
	readBuffer.clear();
	readBuffer.flip();
	currentObjectLength = 0;
	try {
		this.socketChannel = socketChannel;
		socketChannel.configureBlocking(false);
		Socket socket = socketChannel.socket();
		socket.setTcpNoDelay(true);

		selectionKey = socketChannel.register(selector, SelectionKey.OP_READ);

		if (DEBUG) {
			debug("kryonet", "Port " + socketChannel.socket().getLocalPort() + "/TCP connected to: "
				+ socketChannel.socket().getRemoteSocketAddress());
		}

		lastReadTime = lastWriteTime = System.currentTimeMillis();

		return selectionKey;
	} catch (IOException ex) {
		close();
		throw ex;
	}
}
 
Example 5
Source File: ServerSocketChannelTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * @tests ServerSocketChannel#accept().socket()
 */
public void test_write_NonBlocking_RealData() throws Exception {
    serverChannel.configureBlocking(false);
    serverChannel.socket().bind(null);

    byte[] writeContent = new byte[CAPACITY_NORMAL];
    for (int i = 0; i < CAPACITY_NORMAL; i++) {
        writeContent[i] = (byte) i;
    }
    clientChannel.connect(serverChannel.socket().getLocalSocketAddress());

    SocketChannel socketChannel = serverChannel.accept();
    if (socketChannel == null) {
      // Continuous build environment doesn't support non-blocking IO.
      return;
    }
    Socket clientSocket = socketChannel.socket();
    OutputStream out = clientSocket.getOutputStream();
    out.write(writeContent);
    clientSocket.close();
    assertWriteResult(CAPACITY_NORMAL);
}
 
Example 6
Source File: NioAsyncLoadBalanceClient.java    From nifi with Apache License 2.0 6 votes vote down vote up
private SocketChannel createChannel() throws IOException {
    final SocketChannel socketChannel = SocketChannel.open();
    try {
        socketChannel.configureBlocking(true);
        final Socket socket = socketChannel.socket();
        socket.setSoTimeout(timeoutMillis);

        socket.connect(new InetSocketAddress(nodeIdentifier.getLoadBalanceAddress(), nodeIdentifier.getLoadBalancePort()));
        socket.setSoTimeout(timeoutMillis);

        return socketChannel;
    } catch (final Exception e) {
        try {
            socketChannel.close();
        } catch (final Exception closeException) {
            e.addSuppressed(closeException);
        }

        throw e;
    }
}
 
Example 7
Source File: Proxy.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
String toString(SocketChannel ch) {
    StringBuffer sb=new StringBuffer();
    Socket sock;

    if (ch == null)
        return null;
    if ((sock=ch.socket()) == null)
        return null;
    sb.append(sock.getInetAddress().getHostName()).append(':').append(sock.getPort());
    return sb.toString();
}
 
Example 8
Source File: InterruptedStreamTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a pair of connected sockets backed by NIO socket channels.
 */
private Socket[] newSocketChannelPair() throws IOException {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.socket().bind(new InetSocketAddress(0));
    SocketChannel clientSocketChannel = SocketChannel.open();
    clientSocketChannel.connect(serverSocketChannel.socket().getLocalSocketAddress());
    SocketChannel server = serverSocketChannel.accept();
    serverSocketChannel.close();
    return new Socket[] { clientSocketChannel.socket(), server.socket() };
}
 
Example 9
Source File: TcpProxyServer.java    From NetBare with MIT License 5 votes vote down vote up
private void onAccept() throws IOException {
    SocketChannel clientChannel = mServerSocketChannel.accept();
    Socket clientSocket = clientChannel.socket();

    // The client ip is the remote server ip
    // The client port is the local port(it is the vpn port not the proxy server port)
    String ip = clientSocket.getInetAddress().getHostAddress();
    int port = clientSocket.getPort();

    // The session should have be saved before the tcp packets be forwarded to proxy server. So
    // we can query it by client port.
    Session session = mSessionProvider.query((short) port);
    if (session == null) {
        throw new IOException("No session saved with key: " + port);
    }

    int remotePort = NetBareUtils.convertPort(session.remotePort);

    // Connect remote server and dispatch data.
    TcpTunnel proxyTunnel = null;
    TcpTunnel remoteTunnel = null;
    try {
        proxyTunnel = new TcpProxyTunnel(clientChannel, mSelector, remotePort);
        remoteTunnel = new TcpRemoteTunnel(mVpnService, SocketChannel.open(),
                mSelector, ip, remotePort);
        TcpVATunnel gatewayTunnel = new TcpVATunnel(session, proxyTunnel,
                remoteTunnel, mMtu);
        gatewayTunnel.connect(new InetSocketAddress(ip, remotePort));
    } catch (IOException e){
        NetBareUtils.closeQuietly(proxyTunnel);
        NetBareUtils.closeQuietly(remoteTunnel);
        throw e;
    }
}
 
Example 10
Source File: FrontendConnection.java    From heisenberg with Apache License 2.0 5 votes vote down vote up
public FrontendConnection(SocketChannel channel) {
    super(channel);
    Socket socket = channel.socket();
    this.host = socket.getInetAddress().getHostAddress();
    this.port = socket.getPort();
    this.localPort = socket.getLocalPort();
    this.handler = new FrontendAuthenticator(this);
}
 
Example 11
Source File: TNonblockingSocket.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
private TNonblockingSocket(SocketChannel socketChannel, int timeout, SocketAddress socketAddress)
    throws IOException {
  socketChannel_ = socketChannel;
  socketAddress_ = socketAddress;

  // make it a nonblocking channel
  socketChannel.configureBlocking(false);

  // set options
  Socket socket = socketChannel.socket();
  socket.setSoLinger(false, 0);
  socket.setTcpNoDelay(true);
  setTimeout(timeout);
}
 
Example 12
Source File: FrontendConnectionFactory.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
public FrontendConnection make(SocketChannel channel) throws IOException {
    Socket socket = channel.socket();
    socket.setReceiveBufferSize(socketRecvBuffer);
    socket.setSendBufferSize(socketSendBuffer);
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);
    FrontendConnection c = getConnection(channel);
    c.setPacketHeaderSize(packetHeaderSize);
    c.setMaxPacketSize(maxPacketSize);
    c.setWriteQueue(new BufferQueue(writeQueueCapcity));
    c.setIdleTimeout(idleTimeout);
    c.setCharset(charset);
    return c;
}
 
Example 13
Source File: NioEndpoint.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 *
 * 处理特别的连接。
 * Process the specified connection.
 * @param socket The socket channel
 * @return <code>true</code> if the socket was correctly configured
 *  and processing may continue, <code>false</code> if the socket needs to be
 *  close immediately
 *  true 和 false 取决于socket是否能够正确的执行。
 *
 *
 *  在这里的意图:将SocketChannel 转换成 NioChannel.
 *                然后将NioChannel注册到轮询器。
 *  1.设置SocketChannel属性和对应的Socket并转换为NioChannel。
 *  2.将NioChannel注册到Poller上去。
 */
protected boolean setSocketOptions(SocketChannel socket) {
    // Process the connection
    try {
        //disable blocking, APR style, we are gonna be polling it
        //禁止用阻塞,ARP的风格。我门要轮询他。
        socket.configureBlocking(false);
        Socket sock = socket.socket();
        socketProperties.setProperties(sock);

        NioChannel channel = nioChannels.pop();
        if (channel == null) {
            /**
             * 初始化SocketBufferHandler。
             */
            SocketBufferHandler bufhandler = new SocketBufferHandler(
                    socketProperties.getAppReadBufSize(),
                    socketProperties.getAppWriteBufSize(),
                    socketProperties.getDirectBuffer());
            /**
             * 创建Channel对象。
             */
            if (isSSLEnabled()) {
                channel = new SecureNioChannel(socket, bufhandler, selectorPool, this);
            } else {
                channel = new NioChannel(socket, bufhandler);
            }
        } else {
            channel.setIOChannel(socket);
            channel.reset();
        }
        /**
         * 将NioChannel注册到Poller内。
         */
        getPoller0().register(channel);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        try {
            log.error("",t);
        } catch (Throwable tt) {
            ExceptionUtils.handleThrowable(tt);
        }
        // Tell to close the socket
        return false;
    }
    return true;
}
 
Example 14
Source File: SocketOrChannelAcceptorImpl.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public void accept()
{
    try {
        SocketChannel socketChannel = null;
        Socket socket = null;
        if (serverSocketChannel == null) {
            socket = serverSocket.accept();
        } else {
            socketChannel = serverSocketChannel.accept();
            socket = socketChannel.socket();
        }
        orb.getORBData().getSocketFactory()
            .setAcceptedSocketOptions(this, serverSocket, socket);
        if (orb.transportDebugFlag) {
            dprint(".accept: " +
                   (serverSocketChannel == null
                    ? serverSocket.toString()
                    : serverSocketChannel.toString()));
        }

        CorbaConnection connection =
            new SocketOrChannelConnectionImpl(orb, this, socket);
        if (orb.transportDebugFlag) {
            dprint(".accept: new: " + connection);
        }

        // NOTE: The connection MUST be put in the cache BEFORE being
        // registered with the selector.  Otherwise if the bytes
        // are read on the connection it will attempt a time stamp
        // but the cache will be null, resulting in NPE.
        getConnectionCache().put(this, connection);

        if (connection.shouldRegisterServerReadEvent()) {
            Selector selector = orb.getTransportManager().getSelector(0);
            selector.registerForEvent(connection.getEventHandler());
        }

        getConnectionCache().reclaim();

    } catch (IOException e) {
        if (orb.transportDebugFlag) {
            dprint(".accept:", e);
        }
        orb.getTransportManager().getSelector(0).unregisterForEvent(this);
        // REVISIT - need to close - recreate - then register new one.
        orb.getTransportManager().getSelector(0).registerForEvent(this);
        // NOTE: if register cycling we do not want to shut down ORB
        // since local beans will still work.  Instead one will see
        // a growing log file to alert admin of problem.
    }
}
 
Example 15
Source File: TcpChannelHub.java    From Chronicle-Network with Apache License 2.0 4 votes vote down vote up
@Nullable
SocketChannel openSocketChannel(final InetSocketAddress socketAddress) throws IOException {
    final SocketChannel result = SocketChannel.open();
    @Nullable Selector selector = null;
    boolean failed = true;
    try {
        result.configureBlocking(false);
        Socket socket = result.socket();
        socket.setTcpNoDelay(true);
        socket.setReceiveBufferSize(tcpBufferSize);
        socket.setSendBufferSize(tcpBufferSize);
        socket.setSoTimeout(0);
        socket.setSoLinger(false, 0);
        result.connect(socketAddress);

        selector = Selector.open();
        result.register(selector, SelectionKey.OP_CONNECT);

        int select = selector.select(2500);
        if (select == 0) {
            Jvm.warn().on(TcpChannelHub.class, "Timed out attempting to connect to " + socketAddress);
            return null;
        } else {
            try {
                if (!result.finishConnect())
                    return null;

            } catch (IOException e) {
                if (DEBUG_ENABLED)
                    Jvm.debug().on(TcpChannelHub.class, "Failed to connect to " + socketAddress + " " + e);
                return null;
            }
        }
        failed = false;
        return result;

    } finally {
        Closeable.closeQuietly(selector);
        if (failed)
            Closeable.closeQuietly(result);
    }
}
 
Example 16
Source File: StorageConnection.java    From sstable-tools with Apache License 2.0 4 votes vote down vote up
public boolean connect() {
    long start = System.nanoTime();
    long timeout = TimeUnit.MILLISECONDS.toNanos(DatabaseDescriptor.getRpcTimeout());
    while (System.nanoTime() - start < timeout) {
        targetVersion = 10;
        try {
            SocketChannel channel = SocketChannel.open();
            channel.connect(new InetSocketAddress(host, DatabaseDescriptor.getStoragePort()));
            socket = channel.socket();
            socket.setTcpNoDelay(true);
            if (DatabaseDescriptor.getInternodeSendBufferSize() != 0) {
                try {
                    socket.setSendBufferSize(DatabaseDescriptor.getInternodeSendBufferSize());
                } catch (SocketException se) {
                    System.err.println("Failed to set send buffer size on internode socket." + se);
                }
            }

            // SocketChannel may be null when using SSL
            WritableByteChannel ch = socket.getChannel();
            out = new BufferedDataOutputStreamPlus(ch != null ? ch : Channels.newChannel(socket.getOutputStream()), BUFFER_SIZE);

            out.writeInt(MessagingService.PROTOCOL_MAGIC);
            writeHeader(out, targetVersion, false);
            out.flush();

            DataInputStream in = new DataInputStream(socket.getInputStream());
            int maxTargetVersion = in.readInt();
            MessagingService.instance().setVersion(host, maxTargetVersion);

            out.writeInt(MessagingService.current_version);
            CompactEndpointSerializationHelper.serialize(FBUtilities.getBroadcastAddress(), out);
            out.flush();
            return true;
        } catch (IOException e) {
            socket = null;
            e.printStackTrace();
            System.err.println("unable to connect to " + host + e);
            Uninterruptibles.sleepUninterruptibly(OPEN_RETRY_DELAY, TimeUnit.MILLISECONDS);
        }
    }
    return false;
}
 
Example 17
Source File: ObjectReader.java    From tomcatsrc with Apache License 2.0 2 votes vote down vote up
/**
 * Creates an <code>ObjectReader</code> for a TCP NIO socket channel
 * @param channel - the channel to be read.
 */
public ObjectReader(SocketChannel channel) {
    this(channel.socket());
}
 
Example 18
Source File: IncomingSocketChannelManager.java    From TorrentEngine with GNU General Public License v3.0 2 votes vote down vote up
protected void 
 process( 
int						local_port, 
TransportHelperFilter 	filter )

 {

   SocketChannel	channel = ((TCPTransportHelper)filter.getHelper()).getSocketChannel();
      
   Socket socket = channel.socket();

   //set advanced socket options
   try {
     int so_sndbuf_size = COConfigurationManager.getIntParameter( "network.tcp.socket.SO_SNDBUF" );
     if( so_sndbuf_size > 0 )  socket.setSendBufferSize( so_sndbuf_size );
     
     String ip_tos = COConfigurationManager.getStringParameter( "network.tcp.socket.IPDiffServ" );
     if( ip_tos.length() > 0 )  socket.setTrafficClass( Integer.decode( ip_tos ).intValue() );
   }
   catch( Throwable t ) {
     t.printStackTrace();
   }
   
   AEProxyAddressMapper.AppliedPortMapping applied_mapping = proxy_address_mapper.applyPortMapping( socket.getInetAddress(), socket.getPort());
   
   InetSocketAddress	tcp_address = applied_mapping.getAddress();
   
ConnectionEndpoint	co_ep = new ConnectionEndpoint(tcp_address);

Map<String,Object>	properties = applied_mapping.getProperties();

if ( properties != null ){
	
	co_ep.addProperties( properties );
}

ProtocolEndpointTCP	pe_tcp = (ProtocolEndpointTCP)ProtocolEndpointFactory.createEndpoint( ProtocolEndpoint.PROTOCOL_TCP, co_ep, tcp_address );

Transport transport = new TCPTransportImpl( pe_tcp, filter );

   incoming_manager.addConnection( local_port, filter, transport );
 }
 
Example 19
Source File: NioSocketChannel.java    From netty-4.1.22 with Apache License 2.0 2 votes vote down vote up
/**
 * Create a new instance
 *
 * @param parent    the {@link Channel} which created this instance or {@code null} if it was created by the user
 * @param socket    the {@link SocketChannel} which will be used
 */
public NioSocketChannel(Channel parent, SocketChannel socket) {
    super(parent, socket);
    config = new NioSocketChannelConfig(this, socket.socket());
}
 
Example 20
Source File: ObjectReader.java    From Tomcat8-Source-Read with MIT License 2 votes vote down vote up
/**
 * Creates an <code>ObjectReader</code> for a TCP NIO socket channel
 * @param channel - the channel to be read.
 */
public ObjectReader(SocketChannel channel) {
    this(channel.socket());
}