List of usage examples for io.netty.channel ChannelOption SO_KEEPALIVE
ChannelOption SO_KEEPALIVE
To view the source code for io.netty.channel ChannelOption SO_KEEPALIVE.
Click Source Link
From source file:de.pvsnp.chat.api.connector.ChatServer.java
public void connect() { EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1) EventLoopGroup workerGroup = new NioEventLoopGroup(); // (1) try {//from w ww. ja va 2 s. c om ServerBootstrap bootstrap = new ServerBootstrap(); // (2) bootstrap.group(bossGroup, workerGroup); // (3) bootstrap.channel(NioServerSocketChannel.class);// (4) bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { // 5 @Override protected void initChannel(SocketChannel channel) throws Exception { System.out.println( "Ein Computer hat sich verbunden. IP: " + channel.remoteAddress().getHostName()); // (6) channel.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")), // (2) new LineBasedFrameDecoder(1024), // (3) new StringDecoder(Charset.forName("UTF-8")), // (2) new EchoServerHandler()); c.add(channel); sendMassage(channel); } });// (7) bootstrap.childOption(ChannelOption.SO_KEEPALIVE, keepalive); // (8) ChannelFuture future = bootstrap.bind(port).sync(); // (9) System.out.println("Server gestartet!"); future.channel().closeFuture().sync(); // (10) } catch (Exception ex) { ex.printStackTrace(); } finally { bossGroup.shutdownGracefully(); // (11) workerGroup.shutdownGracefully(); // (11) } }
From source file:de.saxsys.synchronizefx.netty.base.server.NettyBasicServer.java
License:Open Source License
@Override public void start() throws SynchronizeFXException { this.connectionAccptorGroup = new NioEventLoopGroup(); this.clientConnectionGroup = new NioEventLoopGroup(); BasicChannelInitializerServer channelInitializer = createChannelInitializer(); channelInitializer.setTopologyCallback(callback); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(connectionAccptorGroup, clientConnectionGroup).channel(NioServerSocketChannel.class) .childHandler(channelInitializer).childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_KEEPALIVE, true); bootstrap.bind(port).syncUninterruptibly(); }
From source file:de.unipassau.isl.evs.ssh.core.network.Client.java
License:Open Source License
/** * Tries to establish a TCP connection to the Server with the given host and port. * If the connect ist successful, {@link #getHandshakeHandler()} is used to add the * required Handlers to the pipeline./*from w w w . j av a2s . c o m*/ * If the connection fails, {@link #channelClosed(Channel)} is called until to many retries are made and the Client * switches to searching the master via UDP discovery using the {@link UDPDiscoveryClient}. */ private void connectClient(InetSocketAddress address) { Log.i(TAG, "Client connecting to " + address); notifyClientConnecting(address.getHostString(), address.getPort()); // TCP Connection Bootstrap b = new Bootstrap().group(requireComponent(ExecutionServiceComponent.KEY)) .channel(NioSocketChannel.class).handler(getHandshakeHandler()) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) TimeUnit.SECONDS.toMillis(5)); // Wait for the start of the client channelFuture = b.connect(address); channelFuture.addListener(new ChannelFutureListener() { /** * Called once the operation completes, either because the connect was successful or because of an error. */ @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { Log.v(TAG, "Channel open"); channelOpen(future.channel()); } else { Log.v(TAG, "Channel open failed"); channelClosed(future.channel()); } } }); channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() { /** * Called once the connection is closed. */ @Override public void operationComplete(ChannelFuture future) throws Exception { Log.v(TAG, "Channel closed"); channelClosed(future.channel()); } }); }
From source file:de.unipassau.isl.evs.ssh.master.network.Server.java
License:Open Source License
/** * Scotty, start me up!//from w w w .j a v a 2s . c o m * Initializes the netty data pipeline and starts the IO server * * @throws InterruptedException if interrupted while waiting for the startup * @throws IllegalStateException is the Server is already running */ private void startServer() throws InterruptedException { if (isChannelOpen()) { throw new IllegalStateException("Server already running"); } //Setup the Executor and Connection Pool final ExecutionServiceComponent eventLoop = requireComponent(ExecutionServiceComponent.KEY); connections = new DefaultChannelGroup(eventLoop.next()); ServerBootstrap b = new ServerBootstrap().group(eventLoop).channel(NioServerSocketChannel.class) .childHandler(getHandshakeHandler()).childOption(ChannelOption.SO_KEEPALIVE, true); //Bind to ports and wait for the start of the server final int localPort = getLocalPort(); if (localPort < 0 || localPort > 65535) { throw new StartupException("Illegal localPort " + localPort); } localChannel = b.bind(localPort).sync(); final int publicPort = getPublicPort(); if (publicPort >= 0 && publicPort <= 65535 && localPort != publicPort) { publicChannel = b.bind(publicPort).sync(); } Log.i(getClass().getSimpleName(), "Server bound to port " + localChannel.channel() + (publicChannel != null ? " and " + publicChannel.channel() : "")); }
From source file:de.xatc.server.nettybootstrap.atc.ATCServerBootstrap.java
public void initServer() throws java.net.BindException { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); try {/*from ww w.j av a2 s . co m*/ ServerBootstrap b = new ServerBootstrap(); // (2) b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3) .childHandler(new ChannelInitializer<SocketChannel>() { // (4) @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ObjectEncoder()); ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null))); ch.pipeline().addLast(new ATCServerHandler()); } }).option(ChannelOption.SO_BACKLOG, ServerConfig.getMaxConnectionsAllowed()) // (5) .childOption(ChannelOption.SO_KEEPALIVE, ServerConfig.isKeepConnectionsAlive()); // (6) LOG.info("Listening for Data on " + ServerConfig.getAtcIP() + ":" + ServerConfig.getAtcPort()); channelFuture = b.bind(ServerConfig.getAtcIP(), ServerConfig.getAtcPort()).sync(); // (7) } catch (InterruptedException ex) { LOG.error(ex.getLocalizedMessage()); ex.printStackTrace(System.err); } catch (Exception ex) { System.err.println("Exceptoin detected. Exit"); System.exit(-1); } }
From source file:de.xatc.server.nettybootstrap.pilot.DataServerBootstrap.java
public void initServer() { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); try {/*from w w w. j ava2 s . c o m*/ ServerBootstrap b = new ServerBootstrap(); // (2) b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3) .childHandler(new ChannelInitializer<SocketChannel>() { // (4) @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ObjectEncoder()); ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null))); ch.pipeline().addLast(new DataServerHandler()); } }).option(ChannelOption.SO_BACKLOG, ServerConfig.getMaxConnectionsAllowed()) // (5) .childOption(ChannelOption.SO_KEEPALIVE, ServerConfig.isKeepConnectionsAlive()); // (6) LOG.info("Listening for Data on " + ServerConfig.getDataIP() + ":" + ServerConfig.getDataPort()); channelFuture = b.bind(ServerConfig.getDataIP(), ServerConfig.getDataPort()).sync(); // (7) } catch (InterruptedException ex) { LOG.error(ex.getLocalizedMessage()); ex.printStackTrace(System.err); } catch (Exception ex) { System.err.println(" exception caught. Could not startup. Exiting" + ex.getLocalizedMessage()); System.exit(-1); } }
From source file:deven.monitor.client.MonitorClient.java
License:Apache License
private void init() { System.out.println("--> initializing connection to " + host + ":" + port); group = new NioEventLoopGroup(); try {// ww w. j a v a 2 s . c o m CommandInit si = new CommandInit(null, false); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(si); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000); b.option(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.SO_KEEPALIVE, true); // Make the connection attempt. channel = b.connect(host, port).syncUninterruptibly(); // want to monitor the connection to the server s.t. if we loose the // connection, we can try to re-establish it. ClientClosedListener ccl = new ClientClosedListener(this); channel.channel().closeFuture().addListener(ccl); System.out.println(channel.channel().localAddress() + " -> open: " + channel.channel().isOpen() + ", write: " + channel.channel().isWritable() + ", reg: " + channel.channel().isRegistered()); } catch (Throwable ex) { System.out.println("failed to initialize the client connection " + ex.toString()); ex.printStackTrace(); } }
From source file:diskCacheV111.doors.NettyLineBasedDoor.java
License:Open Source License
@Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { try (CDC ignored = CDC.reset(getNucleus().getThisAddress())) { Transfer.initSession(false, true); cdc = new CDC(); }/*from w w w . j a va 2 s . c o m*/ channel = ctx.channel(); channel.config().setOption(ChannelOption.ALLOW_HALF_CLOSURE, true); channel.config().setOption(ChannelOption.TCP_NODELAY, true); channel.config().setOption(ChannelOption.SO_KEEPALIVE, true); }
From source file:dorkbox.network.Client.java
License:Apache License
/** * Starts a REMOTE <b>only</b> client, which will connect to the specified host using the specified Connections Options *//*from w w w .j av a 2s .co m*/ @SuppressWarnings("AutoBoxing") public Client(final Configuration config) throws SecurityException { super(config); String threadName = Client.class.getSimpleName(); this.config = config; boolean hostConfigured = (config.tcpPort > 0 || config.udpPort > 0) && config.host != null; boolean isLocalChannel = config.localChannelName != null; if (isLocalChannel && hostConfigured) { String msg = threadName + " Local channel use and TCP/UDP use are MUTUALLY exclusive. Unable to determine what to do."; logger.error(msg); throw new IllegalArgumentException(msg); } localChannelName = config.localChannelName; hostName = config.host; Bootstrap localBootstrap = null; Bootstrap tcpBootstrap = null; Bootstrap udpBootstrap = null; if (config.localChannelName != null) { localBootstrap = new Bootstrap(); } if (config.tcpPort > 0 || config.udpPort > 0) { if (config.host == null) { throw new IllegalArgumentException("You must define what host you want to connect to."); } if (config.host.equals("0.0.0.0")) { throw new IllegalArgumentException( "You cannot connect to 0.0.0.0, you must define what host you want to connect to."); } } if (config.tcpPort > 0) { tcpBootstrap = new Bootstrap(); } if (config.udpPort > 0) { udpBootstrap = new Bootstrap(); } if (localBootstrap == null && tcpBootstrap == null && udpBootstrap == null) { throw new IllegalArgumentException( "You must define how you want to connect, either LOCAL channel name, TCP port, or UDP port"); } if (config.localChannelName != null) { // no networked bootstraps. LOCAL connection only bootstraps.add(new BootstrapWrapper("LOCAL", config.localChannelName, -1, localBootstrap)); localBootstrap.group(newEventLoop(LOCAL, 1, threadName + "-JVM-BOSS")).channel(LocalChannel.class) .remoteAddress(new LocalAddress(config.localChannelName)) .handler(new RegistrationLocalHandlerClient(threadName, registrationWrapper)); } EventLoopGroup workerEventLoop = null; if (tcpBootstrap != null || udpBootstrap != null) { workerEventLoop = newEventLoop(config.workerThreadPoolSize, threadName); } if (tcpBootstrap != null) { bootstraps.add(new BootstrapWrapper("TCP", config.host, config.tcpPort, tcpBootstrap)); if (OS.isAndroid()) { // android ONLY supports OIO (not NIO) tcpBootstrap.channel(OioSocketChannel.class); } else if (OS.isLinux() && NativeLibrary.isAvailable()) { // epoll network stack is MUCH faster (but only on linux) tcpBootstrap.channel(EpollSocketChannel.class); } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) { // KQueue network stack is MUCH faster (but only on macosx) tcpBootstrap.channel(KQueueSocketChannel.class); } else { tcpBootstrap.channel(NioSocketChannel.class); } tcpBootstrap.group(newEventLoop(1, threadName + "-TCP-BOSS")) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH)) .remoteAddress(config.host, config.tcpPort).handler(new RegistrationRemoteHandlerClientTCP( threadName, registrationWrapper, workerEventLoop)); // android screws up on this!! tcpBootstrap.option(ChannelOption.TCP_NODELAY, !OS.isAndroid()).option(ChannelOption.SO_KEEPALIVE, true); } if (udpBootstrap != null) { bootstraps.add(new BootstrapWrapper("UDP", config.host, config.udpPort, udpBootstrap)); if (OS.isAndroid()) { // android ONLY supports OIO (not NIO) udpBootstrap.channel(OioDatagramChannel.class); } else if (OS.isLinux() && NativeLibrary.isAvailable()) { // epoll network stack is MUCH faster (but only on linux) udpBootstrap.channel(EpollDatagramChannel.class); } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) { // KQueue network stack is MUCH faster (but only on macosx) udpBootstrap.channel(KQueueDatagramChannel.class); } else { udpBootstrap.channel(NioDatagramChannel.class); } udpBootstrap.group(newEventLoop(1, threadName + "-UDP-BOSS")) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) // Netty4 has a default of 2048 bytes as upper limit for datagram packets. .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(EndPoint.udpMaxSize)) .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH)) .localAddress(new InetSocketAddress(0)) // bind to wildcard .remoteAddress(new InetSocketAddress(config.host, config.udpPort)) .handler(new RegistrationRemoteHandlerClientUDP(threadName, registrationWrapper, workerEventLoop)); // Enable to READ and WRITE MULTICAST data (ie, 192.168.1.0) // in order to WRITE: write as normal, just make sure it ends in .255 // in order to LISTEN: // InetAddress group = InetAddress.getByName("203.0.113.0"); // NioDatagramChannel.joinGroup(group); // THEN once done // NioDatagramChannel.leaveGroup(group), close the socket udpBootstrap.option(ChannelOption.SO_BROADCAST, false).option(ChannelOption.SO_SNDBUF, udpMaxSize); } }
From source file:dorkbox.network.Server.java
License:Apache License
/** * Convenience method to starts a server with the specified Connection Options */// ww w. j a v a 2 s . com @SuppressWarnings("AutoBoxing") public Server(Configuration config) throws SecurityException { // watch-out for serialization... it can be NULL incoming. The EndPoint (superclass) sets it, if null, so // you have to make sure to use this.serialization super(config); tcpPort = config.tcpPort; udpPort = config.udpPort; localChannelName = config.localChannelName; if (config.host == null) { // we set this to "0.0.0.0" so that it is clear that we are trying to bind to that address. hostName = "0.0.0.0"; // make it clear that this is what we do (configuration wise) so that variable examination is consistent config.host = hostName; } else { hostName = config.host; } if (localChannelName != null) { localBootstrap = new ServerBootstrap(); } else { localBootstrap = null; } if (tcpPort > 0) { tcpBootstrap = new ServerBootstrap(); } else { tcpBootstrap = null; } if (udpPort > 0) { // This is what allows us to have UDP behave "similar" to TCP, in that a session is established based on the port/ip of the // remote connection. This allows us to reuse channels and have "state" for a UDP connection that normally wouldn't exist. // Additionally, this is what responds to discovery broadcast packets udpBootstrap = new SessionBootstrap(tcpPort, udpPort); } else { udpBootstrap = null; } String threadName = Server.class.getSimpleName(); // always use local channels on the server. if (localBootstrap != null) { localBootstrap .group(newEventLoop(LOCAL, 1, threadName + "-JVM-BOSS"), newEventLoop(LOCAL, 1, threadName)) .channel(LocalServerChannel.class) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH)) .localAddress(new LocalAddress(localChannelName)) .childHandler(new RegistrationLocalHandlerServer(threadName, registrationWrapper)); } EventLoopGroup workerEventLoop = null; if (tcpBootstrap != null || udpBootstrap != null) { workerEventLoop = newEventLoop(config.workerThreadPoolSize, threadName); } if (tcpBootstrap != null) { if (OS.isAndroid()) { // android ONLY supports OIO (not NIO) tcpBootstrap.channel(OioServerSocketChannel.class); } else if (OS.isLinux() && NativeLibrary.isAvailable()) { // epoll network stack is MUCH faster (but only on linux) tcpBootstrap.channel(EpollServerSocketChannel.class); } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) { // KQueue network stack is MUCH faster (but only on macosx) tcpBootstrap.channel(KQueueServerSocketChannel.class); } else { tcpBootstrap.channel(NioServerSocketChannel.class); } // TODO: If we use netty for an HTTP server, // Beside the usual ChannelOptions the Native Transport allows to enable TCP_CORK which may come in handy if you implement a HTTP Server. tcpBootstrap .group(newEventLoop(1, threadName + "-TCP-BOSS"), newEventLoop(1, threadName + "-TCP-REGISTRATION")) .option(ChannelOption.SO_BACKLOG, backlogConnectionCount) .option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH)) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new RegistrationRemoteHandlerServerTCP(threadName, registrationWrapper, workerEventLoop)); // have to check options.host for "0.0.0.0". we don't bind to "0.0.0.0", we bind to "null" to get the "any" address! if (hostName.equals("0.0.0.0")) { tcpBootstrap.localAddress(tcpPort); } else { tcpBootstrap.localAddress(hostName, tcpPort); } // android screws up on this!! tcpBootstrap.option(ChannelOption.TCP_NODELAY, !OS.isAndroid()).childOption(ChannelOption.TCP_NODELAY, !OS.isAndroid()); } if (udpBootstrap != null) { if (OS.isAndroid()) { // android ONLY supports OIO (not NIO) udpBootstrap.channel(OioDatagramChannel.class); } else if (OS.isLinux() && NativeLibrary.isAvailable()) { // epoll network stack is MUCH faster (but only on linux) udpBootstrap.channel(EpollDatagramChannel.class); } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) { // KQueue network stack is MUCH faster (but only on macosx) udpBootstrap.channel(KQueueDatagramChannel.class); } else { // windows and linux/mac that are incompatible with the native implementations udpBootstrap.channel(NioDatagramChannel.class); } // Netty4 has a default of 2048 bytes as upper limit for datagram packets, we want this to be whatever we specify FixedRecvByteBufAllocator recvByteBufAllocator = new FixedRecvByteBufAllocator(EndPoint.udpMaxSize); udpBootstrap .group(newEventLoop(1, threadName + "-UDP-BOSS"), newEventLoop(1, threadName + "-UDP-REGISTRATION")) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator) .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH)) // a non-root user can't receive a broadcast packet on *nix if the socket is bound on non-wildcard address. // TODO: move broadcast to it's own handler, and have UDP server be able to be bound to a specific IP // OF NOTE: At the end in my case I decided to bind to .255 broadcast address on Linux systems. (to receive broadcast packets) .localAddress(udpPort) // if you bind to a specific interface, Linux will be unable to receive broadcast packets! see: http://developerweb.net/viewtopic.php?id=5722 .childHandler(new RegistrationRemoteHandlerServerUDP(threadName, registrationWrapper, workerEventLoop)); // // have to check options.host for null. we don't bind to 0.0.0.0, we bind to "null" to get the "any" address! // if (hostName.equals("0.0.0.0")) { // udpBootstrap.localAddress(hostName, tcpPort); // } // else { // udpBootstrap.localAddress(udpPort); // } // Enable to READ from MULTICAST data (ie, 192.168.1.0) // in order to WRITE: write as normal, just make sure it ends in .255 // in order to LISTEN: // InetAddress group = InetAddress.getByName("203.0.113.0"); // socket.joinGroup(group); // THEN once done // socket.leaveGroup(group), close the socket // Enable to WRITE to MULTICAST data (ie, 192.168.1.0) udpBootstrap.option(ChannelOption.SO_BROADCAST, false).option(ChannelOption.SO_SNDBUF, udpMaxSize); } }