Search in sources :

Example 11 with SocketOption

use of java.net.SocketOption in project smart-socket by smartboot.

the class AioQuickServer method start0.

/**
 * 内部启动逻辑
 *
 * @param aioSessionFunction 实例化会话的Function
 * @throws IOException IO异常
 */
private void start0(Function<AsynchronousSocketChannel, TcpAioSession> aioSessionFunction) throws IOException {
    checkAndResetConfig();
    try {
        aioWriteCompletionHandler = new WriteCompletionHandler();
        if (bufferPool == null) {
            this.bufferPool = config.getBufferFactory().create();
            this.innerBufferPool = bufferPool;
        }
        this.aioSessionFunction = aioSessionFunction;
        AsynchronousChannelProvider provider;
        if (config.isAioEnhance()) {
            aioReadCompletionHandler = new ReadCompletionHandler();
            provider = new EnhanceAsynchronousChannelProvider();
        } else {
            concurrentReadCompletionHandlerExecutor = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
            aioReadCompletionHandler = new ConcurrentReadCompletionHandler(new Semaphore(config.getThreadNum() - 1), concurrentReadCompletionHandlerExecutor);
            provider = AsynchronousChannelProvider.provider();
        }
        asynchronousChannelGroup = provider.openAsynchronousChannelGroup(config.getThreadNum(), new ThreadFactory() {

            private byte index = 0;

            @Override
            public Thread newThread(Runnable r) {
                return bufferPool.newThread(r, "smart-socket:Thread-" + (++index));
            }
        });
        this.serverSocketChannel = AsynchronousServerSocketChannel.open(asynchronousChannelGroup);
        // set socket options
        if (config.getSocketOptions() != null) {
            for (Map.Entry<SocketOption<Object>, Object> entry : config.getSocketOptions().entrySet()) {
                this.serverSocketChannel.setOption(entry.getKey(), entry.getValue());
            }
        }
        // bind host
        if (config.getHost() != null) {
            serverSocketChannel.bind(new InetSocketAddress(config.getHost(), config.getPort()), config.getBacklog());
        } else {
            serverSocketChannel.bind(new InetSocketAddress(config.getPort()), config.getBacklog());
        }
        startAcceptThread();
    } catch (IOException e) {
        shutdown();
        throw e;
    }
    System.out.println("smart-socket server started on port " + config.getPort() + ",threadNum:" + config.getThreadNum());
    System.out.println("smart-socket server config is " + config);
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) EnhanceAsynchronousChannelProvider(org.smartboot.socket.enhance.EnhanceAsynchronousChannelProvider) InetSocketAddress(java.net.InetSocketAddress) Semaphore(java.util.concurrent.Semaphore) IOException(java.io.IOException) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) EnhanceAsynchronousChannelProvider(org.smartboot.socket.enhance.EnhanceAsynchronousChannelProvider) AsynchronousChannelProvider(java.nio.channels.spi.AsynchronousChannelProvider) SocketOption(java.net.SocketOption) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) Map(java.util.Map)

Example 12 with SocketOption

use of java.net.SocketOption in project mina-sshd by apache.

the class Nio2Service method setSocketOptions.

@SuppressWarnings("unchecked")
protected <S extends NetworkChannel> S setSocketOptions(S socket) throws IOException {
    Collection<? extends SocketOption<?>> supported = socket.supportedOptions();
    if (GenericUtils.isEmpty(supported)) {
        return socket;
    }
    for (Map.Entry<Property<?>, ? extends Map.Entry<SocketOption<?>, ?>> ce : CONFIGURABLE_OPTIONS.entrySet()) {
        Property<?> property = ce.getKey();
        Map.Entry<SocketOption<?>, ?> defConfig = ce.getValue();
        @SuppressWarnings("rawtypes") SocketOption option = defConfig.getKey();
        setOption(socket, property, option, defConfig.getValue());
    }
    return socket;
}
Also used : SocketOption(java.net.SocketOption) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Property(org.apache.sshd.common.Property)

Example 13 with SocketOption

use of java.net.SocketOption in project mina-sshd by apache.

the class Nio2ServiceTest method testSetSocketOptions.

// see SSHD-554, SSHD-722
@Test
public void testSetSocketOptions() throws Exception {
    try (SshServer sshd = setupTestServer()) {
        Map<Property<?>, Object> expectedOptions = new LinkedHashMap<>();
        expectedOptions.put(CoreModuleProperties.SOCKET_KEEPALIVE, true);
        expectedOptions.put(CoreModuleProperties.SOCKET_LINGER, 5);
        expectedOptions.put(CoreModuleProperties.SOCKET_RCVBUF, 1024);
        expectedOptions.put(CoreModuleProperties.SOCKET_REUSEADDR, true);
        expectedOptions.put(CoreModuleProperties.SOCKET_SNDBUF, 1024);
        expectedOptions.put(CoreModuleProperties.TCP_NODELAY, true);
        for (Map.Entry<Property<?>, ?> oe : expectedOptions.entrySet()) {
            PropertyResolverUtils.updateProperty(sshd, oe.getKey().getName(), oe.getValue());
        }
        Semaphore sigSem = new Semaphore(0, true);
        Map<SocketOption<?>, Map.Entry<?, ?>> actualOptionValues = new HashMap<>(expectedOptions.size());
        sshd.setSessionFactory(new SessionFactory(sshd) {

            @Override
            protected ServerSessionImpl doCreateSession(IoSession ioSession) throws Exception {
                validateSocketOptions(ioSession);
                sigSem.release();
                return super.doCreateSession(ioSession);
            }

            private void validateSocketOptions(IoSession ioSession) throws Exception {
                if (!(ioSession instanceof Nio2Session)) {
                    return;
                }
                AsynchronousSocketChannel socket = ((Nio2Session) ioSession).getSocket();
                Collection<? extends SocketOption<?>> supported = socket.supportedOptions();
                if (GenericUtils.isEmpty(supported)) {
                    return;
                }
                for (Map.Entry<Property<?>, ?> oe : expectedOptions.entrySet()) {
                    Property<?> prop = oe.getKey();
                    Object expValue = oe.getValue();
                    Map.Entry<SocketOption<?>, ?> optionEntry = Nio2Service.CONFIGURABLE_OPTIONS.get(prop);
                    SocketOption<?> option = optionEntry.getKey();
                    if (!supported.contains(option)) {
                        continue;
                    }
                    Object actValue = socket.getOption(option);
                    actualOptionValues.put(option, new SimpleImmutableEntry<>(expValue, actValue));
                }
            }
        });
        sshd.start();
        int port = sshd.getPort();
        long startTime = System.nanoTime();
        try (Socket s = new Socket(TEST_LOCALHOST, port)) {
            long endTime = System.nanoTime();
            long duration = endTime - startTime;
            assertTrue("Connect duration is too high: " + duration, duration <= TimeUnit.SECONDS.toNanos(15L));
            assertTrue("Validation not completed on time", sigSem.tryAcquire(15L, TimeUnit.SECONDS));
        } finally {
            sshd.stop();
        }
        // they might ignore it
        for (Map.Entry<SocketOption<?>, ? extends Map.Entry<?, ?>> mme : actualOptionValues.entrySet()) {
            SocketOption<?> option = mme.getKey();
            Map.Entry<?, ?> vp = mme.getValue();
            Object expValue = vp.getKey();
            Object actValue = vp.getValue();
            Appendable output = Objects.equals(expValue, actValue) ? System.out : System.err;
            output.append('\t').append(option.name()).append(": expected=").append(Objects.toString(expValue)).append(", actual=").append(Objects.toString(actValue)).append(System.lineSeparator());
            if (output instanceof Flushable) {
                ((Flushable) output).flush();
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Semaphore(java.util.concurrent.Semaphore) SshServer(org.apache.sshd.server.SshServer) LinkedHashMap(java.util.LinkedHashMap) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) ServerSessionImpl(org.apache.sshd.server.session.ServerSessionImpl) Property(org.apache.sshd.common.Property) IoSession(org.apache.sshd.common.io.IoSession) SessionFactory(org.apache.sshd.server.session.SessionFactory) Flushable(java.io.Flushable) SocketOption(java.net.SocketOption) AsynchronousSocketChannel(java.nio.channels.AsynchronousSocketChannel) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) Collection(java.util.Collection) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Socket(java.net.Socket) Test(org.junit.Test)

Aggregations

SocketOption (java.net.SocketOption)13 IOException (java.io.IOException)6 Map (java.util.Map)4 InetSocketAddress (java.net.InetSocketAddress)3 AsynchronousSocketChannel (java.nio.channels.AsynchronousSocketChannel)3 BlockingHttpClient (io.servicetalk.http.api.BlockingHttpClient)2 HttpServerBuilder (io.servicetalk.http.api.HttpServerBuilder)2 DefaultTestCerts (io.servicetalk.test.resources.DefaultTestCerts)2 ClientSslConfigBuilder (io.servicetalk.transport.api.ClientSslConfigBuilder)2 ServerContext (io.servicetalk.transport.api.ServerContext)2 ServerSslConfigBuilder (io.servicetalk.transport.api.ServerSslConfigBuilder)2 Field (java.lang.reflect.Field)2 LinkedHashMap (java.util.LinkedHashMap)2 Semaphore (java.util.concurrent.Semaphore)2 SSLException (javax.net.ssl.SSLException)2 Property (org.apache.sshd.common.Property)2 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)2 MethodSource (org.junit.jupiter.params.provider.MethodSource)2 HostAndPort (io.servicetalk.transport.api.HostAndPort)1 AddressUtils.serverHostAndPort (io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort)1