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:eu.heronnet.module.kad.net.ServerImpl.java
License:Open Source License
@Override protected void startUp() throws Exception { logger.debug("calling startUp for ServerImpl instance={}", this); tcpBoostrap = new ServerBootstrap(); udpbootrap = new Bootstrap(); bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); tcpBoostrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(6565) .childHandler(tcpChannelInitializer).option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); tcpBoostrap.bind().sync();/* w w w .j a va 2 s .com*/ udpbootrap.group(workerGroup).channel(NioDatagramChannel.class).localAddress(6565) .handler(udpChannelInitializer).option(ChannelOption.SO_BROADCAST, true); udpbootrap.bind().sync(); }
From source file:eu.jangos.realm.RealmServer.java
License:Apache License
/** * Main of the RealmServer program.//ww w. j av a 2 s . c o m * * @param args the command line arguments * @throws InterruptedException in case of interruption of the running * process. */ public static void main(String[] args) throws InterruptedException { logger.info("Starting JaNGOS realm server version " + VERSION + "."); logger.info("JaNGOS is an opensource project, check-out : https://github.com/Warkdev/JaNGOSRealm !"); realm.setOffline(false); rs.save(realm); logger.info("Realm configuration: "); logger.info("Name: " + realm.getName()); logger.info("Address: " + realm.getAddress() + ":" + realm.getPort()); logger.info("Type: " + realm.getRealmtype().getType()); logger.info("Timezone: " + realm.getRealmtimezone().getName()); logger.info("Population: " + realm.getPopulation()); logger.info("Players: " + realm.getCountPlayers() + "/" + realm.getMaxPlayers()); // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new RealmPacketDecoder(), new RealmPacketEncoder(), new RealmAuthHandler(), new ReadTimeoutHandler(TIMEOUT), new CharacterHandler()); } }); ChannelFuture f; // Start the server. try { HOST = InetAddress.getByAddress(realm.getAddress().getBytes()); f = b.bind(HOST, PORT).sync(); logger.info("JaNGOS realm server started listening on " + HOST.getHostAddress() + ":" + PORT); } catch (UnknownHostException ex) { f = b.bind(PORT); logger.info("JaNGOS realm server started listening on port " + PORT); } // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { logger.info("JaNGOS realm server shutting down."); // Indicating that this realm is offline. realm.setOffline(true); rs.save(realm); // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:eu.matejkormuth.rpgdavid.starving.remote.RemoteConnectionServer.java
License:Open Source License
private void initializeNetty() { // Initialize Netty. this.bossGroup = new NioEventLoopGroup(1); this.workerGroup = new NioEventLoopGroup(1); this.bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ServerChannelInitializer()).option(ChannelOption.TCP_NODELAY, false) .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.TCP_NODELAY, false); }
From source file:eu.point.client.Client.java
License:Open Source License
/** * The method which creates the bootstrap to connect to the server. * It initializes the pipeline with all the required parameters and functions * for encoding, decoding, etc./*w w w .j a v a 2s . com*/ * It then sends the message to the server. * If the message is a Resource Request, then it also returns the received Resource Offer. * * @param message The message to be sent. * @return The received Resource Offer in case the message was a Resource Request. */ public static TmSdnMessages.TmSdnMessage.ResourceOfferMessage sendMessage(TmSdnMessages.TmSdnMessage message) { EventLoopGroup group = new NioEventLoopGroup(); TmSdnMessages.TmSdnMessage.ResourceOfferMessage resourceOffer = null; handler = new TmSdnClientHandler(message); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, false); //initialize the pipeline b.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ProtobufVarint32FrameDecoder()); pipeline.addLast(new ProtobufDecoder(TmSdnMessages.TmSdnMessage.getDefaultInstance())); pipeline.addLast(new ProtobufVarint32LengthFieldPrepender()); pipeline.addLast(new ProtobufEncoder()); pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(5)); pipeline.addLast(handler); } }); // Make a new connection. ChannelFuture f = b.remoteAddress(serverIP, tcpPort).connect(); try { f.sync(); } catch (Exception e) { e.printStackTrace(); } //if message is resource request, then get the received resource offer and return it. if (f.isSuccess() && message.getType() == TmSdnMessages.TmSdnMessage.TmSdnMessageType.RR) { TmSdnMessages.TmSdnMessage.ResourceOfferMessage resp = handler.resultQueue.take(); if (resp != null) { resourceOffer = resp; } } //close the channel. f.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } return resourceOffer; }
From source file:eu.stratosphere.runtime.io.network.netty.NettyConnectionManager.java
License:Apache License
public NettyConnectionManager(ChannelManager channelManager, InetAddress bindAddress, int bindPort, int bufferSize, int numInThreads, int numOutThreads, int lowWaterMark, int highWaterMark) { this.outConnections = new ConcurrentHashMap<RemoteReceiver, Object>(); this.channelManager = channelManager; // -------------------------------------------------------------------- int defaultNumThreads = Math.max(Runtime.getRuntime().availableProcessors() / 4, 1); numInThreads = (numInThreads == -1) ? defaultNumThreads : numInThreads; numOutThreads = (numOutThreads == -1) ? defaultNumThreads : numOutThreads; LOG.info(String.format("Starting with %d incoming and %d outgoing connection threads.", numInThreads, numOutThreads));//from w ww .ja v a 2 s .co m lowWaterMark = (lowWaterMark == -1) ? bufferSize / 2 : lowWaterMark; highWaterMark = (highWaterMark == -1) ? bufferSize : highWaterMark; LOG.info(String.format("Setting low water mark to %d and high water mark to %d bytes.", lowWaterMark, highWaterMark)); // -------------------------------------------------------------------- // server bootstrap (incoming connections) // -------------------------------------------------------------------- this.in = new ServerBootstrap(); this.in.group(new NioEventLoopGroup(numInThreads)).channel(NioServerSocketChannel.class) .localAddress(bindAddress, bindPort).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { channel.pipeline() .addLast(new InboundEnvelopeDecoder(NettyConnectionManager.this.channelManager)) .addLast(new InboundEnvelopeDispatcherHandler( NettyConnectionManager.this.channelManager)); } }).option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(bufferSize)) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); // -------------------------------------------------------------------- // client bootstrap (outgoing connections) // -------------------------------------------------------------------- this.out = new Bootstrap(); this.out.group(new NioEventLoopGroup(numOutThreads)).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { channel.pipeline().addLast(new OutboundEnvelopeEncoder()); } }).option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, lowWaterMark) .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, highWaterMark) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.TCP_NODELAY, false).option(ChannelOption.SO_KEEPALIVE, true); try { this.in.bind().sync(); } catch (InterruptedException e) { throw new RuntimeException("Could not bind server socket for incoming connections."); } if (LOG.isDebugEnabled()) { new Thread(new Runnable() { @Override public void run() { Date date = new Date(); while (true) { try { Thread.sleep(DEBUG_PRINT_QUEUED_ENVELOPES_EVERY_MS); date.setTime(System.currentTimeMillis()); System.out.println(date); System.out.println(getNonZeroNumQueuedEnvelopes()); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } }
From source file:fr.kissy.zergling_push.MainServer.java
License:Apache License
private void run() throws Exception { final ChannelGroup allPlayers = new DefaultChannelGroup("AllPlayers", GlobalEventExecutor.INSTANCE); final ArrayBlockingQueue<PlayerMessage> messagesQueue = new ArrayBlockingQueue<PlayerMessage>(1024); final World world = new World(); final MainLoop mainLoop = new MainLoop(world, allPlayers, messagesQueue); ScheduledThreadPoolExecutor mainLoopExecutor = new ScheduledThreadPoolExecutor(1); mainLoopExecutor.scheduleAtFixedRate(mainLoop, 0, TICK_RATE, TimeUnit.MILLISECONDS); EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); EventExecutorGroup executorGroup = new DefaultEventExecutorGroup(16); try {/*from www . j a v a 2 s .co m*/ final ServerBootstrap sb = new ServerBootstrap(); sb.childOption(ChannelOption.TCP_NODELAY, true); sb.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(final SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("http-decoder", new HttpServerCodec()); pipeline.addLast("http-aggregator", new HttpObjectAggregator(65536)); pipeline.addLast("websocket-compression", new WebSocketServerCompressionHandler()); pipeline.addLast("websocket-protocol", new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true)); pipeline.addLast(executorGroup, "flatbuffer-message", new FlatBufferMessageHandler(world, messagesQueue)); pipeline.addLast("http-server", new HttpStaticFileServerHandler()); } }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); final Channel ch = sb.bind(8080).sync().channel(); ch.closeFuture().sync(); } catch (Exception e) { throw new RuntimeException("Error while running server", e); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:fr.letroll.ttorrentandroid.client.io.PeerClient.java
License:Apache License
public void start() throws Exception { group = new NioEventLoopGroup(); bootstrap = new Bootstrap(); bootstrap.group(group);//from w ww . ja v a2 s. c o m bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.option(ChannelOption.TCP_NODELAY, true); // bootstrap.option(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES)); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) TimeUnit.SECONDS.toMillis(10)); // bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, (int) TimeUnit.SECONDS.toMillis(10)); }
From source file:fr.letroll.ttorrentandroid.client.io.PeerServer.java
License:Apache License
public void start() throws Exception { group = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(group);/*from w ww . j ava2 s. c o m*/ b.channel(NioServerSocketChannel.class); b.option(ChannelOption.SO_BACKLOG, 128); b.option(ChannelOption.SO_REUSEADDR, true); b.option(ChannelOption.TCP_NODELAY, true); b.childHandler(new PeerServerHandshakeHandler(client)); b.childOption(ChannelOption.SO_KEEPALIVE, true); // b.childOption(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES)); if (address != null) { future = b.bind(address).sync(); } else { BIND: { Exception x = new IOException("No available port for the BitTorrent client!"); for (int i = PORT_RANGE_START; i <= PORT_RANGE_END; i++) { try { future = b.bind(i).sync(); break BIND; } catch (InterruptedException e) { throw e; } catch (Exception e) { x = e; } } throw new IOException("Failed to find an address to bind in range [" + PORT_RANGE_START + "," + PORT_RANGE_END + "]", x); } } }
From source file:gash.router.app.DemoApp.java
License:Apache License
/** * sample application (client) use of our messaging service * /*w w w . ja v a2s . c o m*/ * @param args */ public static void main(String[] args) { String host = "127.0.0.1"; int port = 4568; Boolean affirm = true; Boolean mainAffirm = true; try { // MessageClient mc = new MessageClient(host, port); // DemoApp da = new DemoApp(mc); // do stuff w/ the connection // da.ping(2); // Logger.info("trying to connect to node " + ); if (jedisHandler1.ping().equals("PONG")) { host = jedisHandler1.get("1").split(":")[0]; port = Integer.parseInt(jedisHandler1.get("1").split(":")[1]); } else if (jedisHandler2.ping().equals("PONG")) { host = jedisHandler2.get("1").split(":")[0]; port = Integer.parseInt(jedisHandler2.get("1").split(":")[1]); } else if (jedisHandler3.ping().equals("PONG")) { host = jedisHandler3.get("1").split(":")[0]; port = Integer.parseInt(jedisHandler3.get("1").split(":")[1]); } EventLoopGroup workerGroup = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); // (1) b.group(workerGroup); // (2) b.channel(NioSocketChannel.class); // (3) b.option(ChannelOption.SO_KEEPALIVE, true); // (4) b.handler(new CommandInit(null, false)); // Start the client. System.out.println("Connect to a node."); ChannelFuture f = b.connect(host, port).sync(); // (5) channel = f.channel(); Scanner reader = new Scanner(System.in); try { int option = 0; System.out.println("Welcome to Gossamer Distributed"); System.out.println("Please choose an option to continue: "); System.out.println("1. Read a file"); System.out.println("2. Write a file"); System.out.println("0. Exit"); option = reader.nextInt(); // option = 2; // reader.nextLine(); System.out.println("You entered " + option); System.out.println("Press Y to continue or any other key to cancel"); String ans = ""; // ans=reader.nextLine(); // ans = "Y"; if (ans.equals("Y")) { mainAffirm = false; } String path = ""; switch (option) { case 1: break; case 2: // For testing writes // String path = runWriteTest(); System.out.println("Please enter directory (path) to upload:"); // path = reader.nextLine(); // path = "C:\\Songs\\1.mp4"; System.in.read(); System.out.println("You entered" + path); System.out.println("Press Y to continue or any other key to cancel"); affirm = false; String ans1 = ""; ans1 = reader.next(); // ans1 = "Y"; if (ans1.equals("Y")) { affirm = true; } reader.close(); File file = new File(path); long begin = System.currentTimeMillis(); System.out.println("Begin time"); System.out.println(begin); sendFile(file); System.out.println("File sent"); System.out.flush(); break; } } catch (Exception e) { // TODO Auto-generated catch block System.out.println("Error occurred..."); Thread.sleep(10 * 1000); e.printStackTrace(); } finally { System.out.println("Exiting..."); // Thread.sleep(10 * 1000); } // System.out.println("\n** exiting in 10 seconds. **"); // System.out.flush(); // Thread.sleep(10 * 1000); } catch ( Exception e) { e.printStackTrace(); } finally { // CommConnection.getInstance().release(); } }
From source file:gash.router.client.CommConnection.java
License:Apache License
private void init() { System.out.println("--> initializing connection to " + host + ":" + port); // the queue to support client-side surging outbound = new LinkedBlockingDeque<CommandMessage>(); group = new NioEventLoopGroup(); try {//from w w w.ja v a 2s . com CommInit si = new CommInit(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(); System.out.println("Printing channel " + channel); // 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) { logger.error("failed to initialize the client connection", ex); ex.printStackTrace(); } // start outbound message processor worker = new CommWorker(this); worker.setDaemon(true); worker.start(); }