Java tutorial
/* * Copyright (C) 2014 www.StarNub.org - Underbalanced * * This file is part of org.starnub a Java Wrapper for Starbound. * * This above mentioned StarNub software is free software: * you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or * any later version. This above mentioned CodeHome software * is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU General Public License for more details. You should * have received a copy of the GNU General Public License in * this StarNub Software. If not, see <http://www.gnu.org/licenses/>. */ package org.starnub.utilities.connectivity.client; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import org.starnub.utilities.concurrent.thread.NamedThreadFactory; public class TCPClient { private final EventLoopGroup workerGroup; public TCPClient(String threadName) { workerGroup = new NioEventLoopGroup(1, new NamedThreadFactory(threadName)); } public ChannelFuture connect(String ipAddress, int port, ChannelInitializer<SocketChannel> channelInitializer) { Bootstrap b = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.SO_KEEPALIVE, true).handler(channelInitializer); return b.connect(ipAddress, port); } public void shutdown() { workerGroup.shutdownGracefully(); } }