List of usage examples for io.netty.channel ChannelOption SO_REUSEADDR
ChannelOption SO_REUSEADDR
To view the source code for io.netty.channel ChannelOption SO_REUSEADDR.
Click Source Link
From source file:se.sics.gvod.net.NettyNetwork.java
License:Open Source License
/** * Connect to a TCP server.// ww w . j a va 2 s . c om * * @param remoteAddress the remote address * @param localAddress the local address to bind to * @return true if connection succeeded * @throws ChannelException if connecting failed */ private boolean connectTcp(Address remoteAddress, Address localAddress) { InetSocketAddress remote = address2SocketAddress(remoteAddress); InetSocketAddress local = address2SocketAddress(localAddress); if (tcpSocketsToBootstraps.containsKey(remote)) { return true; } EventLoopGroup group = new NioEventLoopGroup(); NettyStreamHandler handler = new NettyStreamHandler(component, Transport.TCP); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class) .handler(new NettyInitializer<SocketChannel>(handler, msgDecoderClass)) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MS) .option(ChannelOption.SO_REUSEADDR, true); try { SocketChannel c = (SocketChannel) bootstrap.connect(remote, local).sync().channel(); addLocalSocket(remote, c); logger.debug("Successfully connected to ip:port {}", remote.toString()); } catch (InterruptedException e) { logger.warn("Problem when trying to connect to {}", remote); trigger(new Fault(e.getCause()), control); return false; } tcpSocketsToBootstraps.put(remote, bootstrap); return true; }
From source file:se.sics.gvod.net.NettyNetwork.java
License:Open Source License
/** * Connect to a UDT server./*from w w w . j ava 2s . com*/ * * @param remoteAddress the remote address * @param localAddress the local address to bind to * @return true if connection succeeded * @throws ChannelException if connecting failed */ private boolean connectUdt(Address remoteAddress, Address localAddress) { InetSocketAddress remote = address2SocketAddress(remoteAddress); InetSocketAddress local = address2SocketAddress(localAddress); if (udtSocketsToBootstraps.containsKey(remote)) { return true; } ThreadFactory workerFactory = new UtilThreadFactory("clientWorker"); NioEventLoopGroup workerGroup = new NioEventLoopGroup(1, workerFactory, NioUdtProvider.BYTE_PROVIDER); NettyStreamHandler handler = new NettyStreamHandler(component, Transport.UDT); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup).channelFactory(NioUdtProvider.BYTE_CONNECTOR) .handler(new NettyInitializer<UdtChannel>(handler, msgDecoderClass)) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MS) .option(ChannelOption.SO_REUSEADDR, true); try { UdtChannel c = (UdtChannel) bootstrap.connect(remote, local).sync().channel(); addLocalSocket(remote, c); logger.debug("Successfully connected to ip:port {}", remote.toString()); } catch (InterruptedException e) { logger.warn("Problem when trying to connect to {}", remote.toString()); trigger(new Fault(e.getCause()), control); return false; } udtSocketsToBootstraps.put(remote, bootstrap); return true; }
From source file:se.sics.kompics.network.netty.NettyNetwork.java
License:Open Source License
public NettyNetwork(NettyInit init) { System.setProperty("java.net.preferIPv4Stack", "true"); self = init.self;//from w w w . j a v a2 s . c o m boundPort = self.getPort(); // Prepare Bootstraps bootstrapTCPClient = new Bootstrap(); bootstrapTCPClient.group(new NioEventLoopGroup()).channel(NioSocketChannel.class) .handler(new NettyInitializer<SocketChannel>(new StreamHandler(this, Transport.TCP))) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MS) .option(ChannelOption.SO_REUSEADDR, true); bootstrapUDTClient = new Bootstrap(); NioEventLoopGroup groupUDT = new NioEventLoopGroup(1, Executors.defaultThreadFactory(), NioUdtProvider.BYTE_PROVIDER); bootstrapUDTClient.group(groupUDT).channelFactory(NioUdtProvider.BYTE_CONNECTOR) .handler(new NettyInitializer<SocketChannel>(new StreamHandler(this, Transport.UDT))) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MS) .option(ChannelOption.SO_REUSEADDR, true); subscribe(startHandler, control); subscribe(stopHandler, control); subscribe(msgHandler, net); subscribe(notifyHandler, net); }
From source file:se.sics.kompics.network.netty.NettyNetwork.java
License:Open Source License
private boolean bindUdpPort(final InetAddress addr, final int port) { EventLoopGroup group = new NioEventLoopGroup(); bootstrapUDP = new Bootstrap(); bootstrapUDP.group(group).channel(NioDatagramChannel.class) .handler(new DatagramHandler(this, Transport.UDP)); bootstrapUDP.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(1500, 1500, RECV_BUFFER_SIZE)); bootstrapUDP.option(ChannelOption.SO_RCVBUF, RECV_BUFFER_SIZE); bootstrapUDP.option(ChannelOption.SO_SNDBUF, SEND_BUFFER_SIZE); // bootstrap.setOption("trafficClass", trafficClass); // bootstrap.setOption("soTimeout", soTimeout); // bootstrap.setOption("broadcast", broadcast); bootstrapUDP.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MS); bootstrapUDP.option(ChannelOption.SO_REUSEADDR, true); try {/* w w w.ja v a 2s .c o m*/ InetSocketAddress iAddr = new InetSocketAddress(addr, port); DatagramChannel c = (DatagramChannel) bootstrapUDP.bind(iAddr).sync().channel(); addLocalSocket(iAddr, c); LOG.info("Successfully bound to ip:port {}:{}", addr, port); } catch (InterruptedException e) { LOG.error("Problem when trying to bind to {}:{}", addr.getHostAddress(), port); return false; } return true; }
From source file:se.sics.kompics.network.netty.NettyNetwork.java
License:Open Source License
private boolean bindTcpPort(InetAddress addr, int port) { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); TCPServerHandler handler = new TCPServerHandler(this); bootstrapTCP = new ServerBootstrap(); bootstrapTCP.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler((new NettyInitializer<SocketChannel>(handler))) .option(ChannelOption.SO_REUSEADDR, true); try {//from w w w.j av a 2 s . c om bootstrapTCP.bind(new InetSocketAddress(addr, port)).sync(); LOG.info("Successfully bound to ip:port {}:{}", addr, port); } catch (InterruptedException e) { LOG.error("Problem when trying to bind to {}:{}", addr, port); return false; } //InetSocketAddress iAddr = new InetSocketAddress(addr, port); return true; }
From source file:se.sics.kompics.network.netty.NettyNetwork.java
License:Open Source License
private boolean bindUdtPort(InetAddress addr) { ThreadFactory bossFactory = Executors.defaultThreadFactory(); ThreadFactory workerFactory = Executors.defaultThreadFactory(); NioEventLoopGroup bossGroup = new NioEventLoopGroup(1, bossFactory, NioUdtProvider.BYTE_PROVIDER); NioEventLoopGroup workerGroup = new NioEventLoopGroup(1, workerFactory, NioUdtProvider.BYTE_PROVIDER); UDTServerHandler handler = new UDTServerHandler(this); bootstrapUDT = new ServerBootstrap(); bootstrapUDT.group(bossGroup, workerGroup).channelFactory(NioUdtProvider.BYTE_ACCEPTOR) .childHandler(new NettyInitializer<UdtChannel>(handler)).option(ChannelOption.SO_REUSEADDR, true); try {//from w ww . j a v a 2 s . com Channel c = bootstrapUDT.bind(addr, 0).sync().channel(); InetSocketAddress localAddress = (InetSocketAddress) c.localAddress(); // Should work boundUDTPort = localAddress.getPort(); LOG.info("Successfully bound UDT to ip:port {}:{}", addr, boundUDTPort); } catch (InterruptedException e) { LOG.error("Problem when trying to bind UDT to {}", addr); return false; } return true; }
From source file:sh.lab.jcorrelat.App.java
License:Open Source License
public static void main(final String[] args) throws Exception { ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME)) .setLevel(CONF_LOG_LEVEL);/*w w w . jav a 2s .com*/ final EventLoopGroup bossGroup = new NioEventLoopGroup(); final EventLoopGroup workerGroup = new NioEventLoopGroup(); final MessagePersister persister = new MessagePersister(); final EventExecutorGroup correlatorGroup = new DefaultEventExecutorGroup(32); final MessageCorrelationHandler correlatorHandler = new MessageCorrelationHandler(persister); try { final ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(final SocketChannel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast("framer", new LineBasedFrameDecoder(MessageDecoder.BUFFER_SIZE)); pipeline.addLast("decoder", new MessageDecoder()); pipeline.addLast(/*correlatorGroup,*/ "correlator", correlatorHandler); } }).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_BACKLOG, 8) .option(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true); final Channel channel = bootstrap.bind(CONF_BIND_HOST, CONF_BIND_PORT).sync().channel(); channel.closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }
From source file:storage.netty.HTTPUploadClientAsync.java
License:Apache License
public void putBlob(String filepath) throws Exception { String resourceUrl = "/mycontainer/" + randomString(5); String putBlobUrl = base_url + resourceUrl; URI uriSimple = new URI(putBlobUrl); String scheme = uriSimple.getScheme() == null ? "http" : uriSimple.getScheme(); String host = uriSimple.getHost() == null ? "127.0.0.1" : uriSimple.getHost(); int port = uriSimple.getPort(); if (port == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80;//from w w w . j a va2 s . c o m } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } } if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { System.err.println("Only HTTP(S) is supported."); return; } final boolean ssl = "https".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } File path = new File(filepath); if (!path.canRead()) { throw new FileNotFoundException(filepath); } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); // setup the factory: here using a mixed memory/disk based on size threshold HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if MINSIZE exceed DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit) DiskFileUpload.baseDirectory = null; // system temp directory DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit) DiskAttribute.baseDirectory = null; // system temp directory try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new HttpUploadClientInitializer(sslCtx)); b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 10 * 64 * 1024); b.option(ChannelOption.SO_SNDBUF, 1048576); b.option(ChannelOption.SO_RCVBUF, 1048576); b.option(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.SO_REUSEADDR, true); b.option(ChannelOption.AUTO_CLOSE, true); //Iterate over files Collection<ChannelFuture> futures = new ArrayList<ChannelFuture>(); for (final File file : path.listFiles()) { String blobname = file.getName(); System.out.println(blobname); HttpRequest request = formpost(host, port, resourceUrl + blobname, file, factory); ChannelFuture cf = b.connect(host, port); futures.add(cf); cf.channel().attr(HTTPREQUEST).set(request); cf.channel().attr(FILETOUPLOAD).set(file); cf.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { // check to see if we succeeded if (future.isSuccess()) { System.out.println("connected for " + blobname); } else { System.out.println(future.cause().getMessage()); } } }); } for (ChannelFuture cf : futures) { cf.channel().closeFuture().awaitUninterruptibly(); } } finally { // Shut down executor threads to exit. group.shutdownGracefully(); // Really clean all temporary files if they still exist factory.cleanAllHttpDatas(); } }