public void start() throws InterruptedException {
final EventLoopGroup workerGroup = Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workerGroup)
.channel(Epoll.isAvailable() ? EpollSocketChannel.class : NioSocketChannel.class)
.handler(new OpenCloudChannelInitializer(this))
.connect(this.host, this.port).sync().channel().closeFuture().syncUninterruptibly();
} catch (Exception ex) {
if (ex.getClass().getSimpleName().equals("AnnotatedConnectException")) {
System.err.println("Cannot connect to master!");
channel.close();
} else {
ex.printStackTrace();
}
} finally {
workerGroup.shutdownGracefully();
System.out.println("Netty client stopped");
Runtime.getRuntime().halt(0);
}
}
java类io.netty.channel.epoll.Epoll的实例源码
Client.java 文件源码
项目:CentauriCloud
阅读 32
收藏 0
点赞 0
评论 0
AbstractNettyServer.java 文件源码
项目:Limitart
阅读 32
收藏 0
点赞 0
评论 0
protected AbstractNettyServer(String serverName) {
this.serverName = Objects.requireNonNull(serverName, "server name");
bootstrap = new ServerBootstrap();
if (Epoll.isAvailable()) {
bootstrap.option(ChannelOption.SO_BACKLOG, 1024).channel(EpollServerSocketChannel.class)
.childOption(ChannelOption.SO_LINGER, 0).childOption(ChannelOption.SO_REUSEADDR, true)
.childOption(ChannelOption.SO_KEEPALIVE, true);
log.info(serverName + " epoll init");
} else {
bootstrap.channel(NioServerSocketChannel.class);
log.info(serverName + " nio init");
}
bootstrap.group(bossGroup, workerGroup).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
initPipeline(ch.pipeline());
}
});
}
ConnectionProvider.java 文件源码
项目:UnknownPandaServer
阅读 26
收藏 0
点赞 0
评论 0
public void start() throws Exception {
UnknownPandaServer.getLogger().info("Loading protocol");
Protocol protocol = ProtocolSpecification.getProtocol();
protocol.load();
UnknownPandaServer.getLogger().info("Binding UniverseServer at *::" + port + " [tcp]");
this.channel = new ServerBootstrap()
.group(Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup())
.channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
//.childOption(ChannelOption.TCP_NODELAY, true)
.childHandler(new ConnectionInitializer(this))
.localAddress("", port)
.bind()
.addListeners(this)
.sync()
.channel();
}
ServerConnection.java 文件源码
项目:Diorite-old
阅读 36
收藏 0
点赞 0
评论 0
@Override
public void init(final InetAddress address, final int port, final boolean useEpoll)
{
final Class<? extends ServerSocketChannel> socketChannelClass;
final LazyValue<? extends EventLoopGroup> lazyInit;
if ((Epoll.isAvailable()) && useEpoll)
{
socketChannelClass = EpollServerSocketChannel.class;
lazyInit = this.epollEventLoopGroupLazyValue;
CoreMain.debug("[Netty] Using epoll channel type");
}
else
{
socketChannelClass = NioServerSocketChannel.class;
lazyInit = this.nioEventLoopGroupLazyValue;
CoreMain.debug("[Netty] Using default channel type");
}
this.channelFuture = new ServerBootstrap().channel(socketChannelClass).childHandler(new ServerConnectionChannel(this)).group(lazyInit.get()).localAddress(address, port).bind().syncUninterruptibly();
}
ClientConnection.java 文件源码
项目:Diorite-old
阅读 38
收藏 0
点赞 0
评论 0
@Override
public void init(final InetAddress address, final int port, final boolean useEpoll)
{
final Class<? extends SocketChannel> socketChannelClass;
final LazyValue<? extends EventLoopGroup> lazyInit;
if ((Epoll.isAvailable()) && useEpoll)
{
socketChannelClass = EpollSocketChannel.class;
lazyInit = this.epollEventLoopGroupLazyValue;
CoreMain.debug("[Netty] Using epoll channel type");
}
else
{
socketChannelClass = NioSocketChannel.class;
lazyInit = this.nioEventLoopGroupLazyValue;
CoreMain.debug("[Netty] Using default channel type");
}
this.channelFuture = new Bootstrap().channel(socketChannelClass).handler(new ClientConnectionChannel(this)).group(lazyInit.get()).remoteAddress(address, port).connect().syncUninterruptibly();
}
PubSubClient.java 文件源码
项目:vast-pubsub
阅读 42
收藏 0
点赞 0
评论 0
public void connect(String apiKey) {
Bootstrap bootstrap = new Bootstrap();
Class<? extends Channel> channelClazz;
if (Epoll.isAvailable()) {
channelClazz = EpollSocketChannel.class;
eventLoopGroup = new EpollEventLoopGroup();
} else {
channelClazz = NioSocketChannel.class;
eventLoopGroup = new NioEventLoopGroup();
}
bootstrap.group(eventLoopGroup)
.channel(channelClazz)
.option(ChannelOption.SO_KEEPALIVE, true)
// TODO: add function to get data class by topic and add handler
.remoteAddress(host, port)
.connect();
}
NettyNetworkingService.java 文件源码
项目:Coerce
阅读 31
收藏 0
点赞 0
评论 0
@Override
public void initialise(NetworkChannelHandler channelHandler) {
this.channelHandler = channelHandler;
final boolean useEpoll = this.configuration.getBoolean("epoll") && Epoll.isAvailable();
EventLoopGroup acceptGroup = useEpoll ? new EpollEventLoopGroup(this.configuration.getInt("acceptGroup")) :
new NioEventLoopGroup(this.configuration.getInt("acceptGroup"));
EventLoopGroup ioGroup = useEpoll ? new EpollEventLoopGroup(this.configuration.getInt("ioGroup")) :
new NioEventLoopGroup(this.configuration.getInt("ioGroup"));
EventLoopGroup channelGroup = useEpoll ? new EpollEventLoopGroup(this.configuration.getInt("channelGroup")) :
new NioEventLoopGroup(this.configuration.getInt("channelGroup"));
this.serverBootstrap = new ServerBootstrap()
.group(acceptGroup, ioGroup)
.channel(useEpoll ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
.childHandler(new ChannelInitialiser(channelGroup, this.channelHandler, null))
.option(ChannelOption.SO_BACKLOG, this.configuration.getInt("backlog"))
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT)
.childOption(ChannelOption.TCP_NODELAY, this.configuration.getBoolean("tcpNoDelay"))
.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
}
McpeOverRakNetNetworkListener.java 文件源码
项目:voxelwind
阅读 28
收藏 0
点赞 0
评论 0
public McpeOverRakNetNetworkListener(VoxelwindServer voxelwindServer, String host, int port, boolean useSoReuseport) {
this.server = voxelwindServer;
this.address = new InetSocketAddress(host, port);
this.useSoReuseport = useSoReuseport;
if (Epoll.isAvailable()) {
bootstrap = new Bootstrap()
.channel(EpollDatagramChannel.class)
.group(new EpollEventLoopGroup(0, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("Voxelwind MCPE Listener - #%d").build()))
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.handler(this);
if (useSoReuseport) {
bootstrap.option(EpollChannelOption.SO_REUSEPORT, true);
}
} else {
bootstrap = new Bootstrap()
.channel(NioDatagramChannel.class)
.group(new NioEventLoopGroup(0, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("Voxelwind MCPE Listener - #%d").build()))
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.handler(this);
}
}
RconNetworkListener.java 文件源码
项目:voxelwind
阅读 26
收藏 0
点赞 0
评论 0
@Override
public boolean bind() {
ChannelFuture future = new ServerBootstrap()
.channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.group(group)
.childHandler(this)
.bind(server.getConfiguration().getRcon().getHost(), server.getConfiguration().getRcon().getPort())
.awaitUninterruptibly();
if (future.isSuccess()) {
this.channel = future.channel();
return true;
}
return false;
}
VoxelwindServer.java 文件源码
项目:voxelwind
阅读 26
收藏 0
点赞 0
评论 0
public static void main(String... args) throws Exception {
// RakNet doesn't really like IPv6
ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);
System.setProperty("java.net.preferIPv4Stack", "true");
// Load native libraries early.
boolean partiallySupportedLinux = Epoll.isAvailable();
boolean fullySupportedLinux = NativeCodeFactory.cipher.load();
if (partiallySupportedLinux) {
NativeCodeFactory.zlib.load();
if (fullySupportedLinux) {
NativeCodeFactory.hash.load();
} else {
LOGGER.warn("You are running x64 Linux, but you are not using a fully-supported distribution. Server throughput and performance will be affected. Visit https://wiki.voxelwind.com/why_linux for more information.");
}
} else {
LOGGER.warn("You are not running x64 Linux. Server throughput and performance will be affected. Visit https://wiki.voxelwind.com/why_linux for more information.");
}
VoxelwindServer server = new VoxelwindServer();
server.boot();
}
ServerBase.java 文件源码
项目:LanternServer
阅读 28
收藏 0
点赞 0
评论 0
/**
* Initializes the network server.
*
* @param address The address to bind the server to
* @param useEpollWhenAvailable Whether you want to use epoll if it's available
* @return The channel future
*/
public final ChannelFuture init(SocketAddress address, boolean useEpollWhenAvailable) {
if (this.initialized) {
throw new IllegalStateException("The network server can only be initialized once.");
}
boolean epoll = false;
if (epollAvailabilityLogged) {
epoll = Epoll.isAvailable() && useEpollWhenAvailable;
} else if (useEpollWhenAvailable) {
if (Epoll.isAvailable()) {
epoll = true;
Lantern.getLogger().info("Epoll is enabled.");
} else {
// Debug the reason why it is unavailable
Lantern.getLogger().debug("Epoll is unavailable.", Epoll.unavailabilityCause());
}
epollAvailabilityLogged = true;
}
final ChannelFuture future = init0(address, epoll);
this.initialized = true;
return future;
}
BGPDispatcherImpl.java 文件源码
项目:bgpcep
阅读 32
收藏 0
点赞 0
评论 0
private synchronized ServerBootstrap createServerBootstrap(final ChannelPipelineInitializer initializer) {
final ServerBootstrap serverBootstrap = new ServerBootstrap();
if (Epoll.isAvailable()) {
serverBootstrap.channel(EpollServerSocketChannel.class);
serverBootstrap.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
} else {
serverBootstrap.channel(NioServerSocketChannel.class);
}
final ChannelHandler serverChannelHandler = BGPChannel.createServerChannelHandler(initializer);
serverBootstrap.childHandler(serverChannelHandler);
serverBootstrap.option(ChannelOption.SO_BACKLOG, SOCKET_BACKLOG_SIZE);
serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
serverBootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, WATER_MARK);
// Make sure we are doing round-robin processing
serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(FIX_BUFFER_SIZE));
if (serverBootstrap.config().group() == null) {
serverBootstrap.group(this.bossGroup, this.workerGroup);
}
return serverBootstrap;
}
AbstractBGPDispatcherTest.java 文件源码
项目:bgpcep
阅读 26
收藏 0
点赞 0
评论 0
@Before
public void setUp() throws BGPDocumentedException {
if (!Epoll.isAvailable()) {
this.boss = new NioEventLoopGroup();
this.worker = new NioEventLoopGroup();
}
this.registry = new StrictBGPPeerRegistry();
this.clientListener = new SimpleSessionListener();
this.serverListener = new SimpleSessionListener();
final BGPExtensionProviderContext ctx = ServiceLoaderBGPExtensionProviderContext.getSingletonInstance();
this.serverDispatcher = new BGPDispatcherImpl(ctx.getMessageRegistry(), this.boss, this.worker, this.registry);
this.clientAddress = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress();
final IpAddress clientPeerIp = new IpAddress(new Ipv4Address(this.clientAddress.getAddress().getHostAddress()));
this.registry.addPeer(clientPeerIp, this.clientListener, createPreferences(this.clientAddress));
this.clientDispatcher = new BGPDispatcherImpl(ctx.getMessageRegistry(), this.boss, this.worker, this.registry);
}
NetworkManager.java 文件源码
项目:DecompiledMinecraft
阅读 30
收藏 0
点赞 0
评论 0
public static NetworkManager func_181124_a(InetAddress p_181124_0_, int p_181124_1_, boolean p_181124_2_)
{
final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
Class <? extends SocketChannel > oclass;
LazyLoadBase <? extends EventLoopGroup > lazyloadbase;
if (Epoll.isAvailable() && p_181124_2_)
{
oclass = EpollSocketChannel.class;
lazyloadbase = field_181125_e;
}
else
{
oclass = NioSocketChannel.class;
lazyloadbase = CLIENT_NIO_EVENTLOOP;
}
((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer<Channel>()
{
protected void initChannel(Channel p_initChannel_1_) throws Exception
{
try
{
p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true));
}
catch (ChannelException var3)
{
;
}
p_initChannel_1_.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter", (ChannelHandler)(new MessageDeserializer2())).addLast((String)"decoder", (ChannelHandler)(new MessageDeserializer(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender", (ChannelHandler)(new MessageSerializer2())).addLast((String)"encoder", (ChannelHandler)(new MessageSerializer(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler", (ChannelHandler)networkmanager);
}
})).channel(oclass)).connect(p_181124_0_, p_181124_1_).syncUninterruptibly();
return networkmanager;
}
NetworkManager.java 文件源码
项目:BaseClient
阅读 26
收藏 0
点赞 0
评论 0
public static NetworkManager func_181124_a(InetAddress p_181124_0_, int p_181124_1_, boolean p_181124_2_)
{
final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
Class <? extends SocketChannel > oclass;
LazyLoadBase <? extends EventLoopGroup > lazyloadbase;
if (Epoll.isAvailable() && p_181124_2_)
{
oclass = EpollSocketChannel.class;
lazyloadbase = field_181125_e;
}
else
{
oclass = NioSocketChannel.class;
lazyloadbase = CLIENT_NIO_EVENTLOOP;
}
((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer<Channel>()
{
protected void initChannel(Channel p_initChannel_1_) throws Exception
{
try
{
p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true));
}
catch (ChannelException var3)
{
;
}
p_initChannel_1_.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter", (ChannelHandler)(new MessageDeserializer2())).addLast((String)"decoder", (ChannelHandler)(new MessageDeserializer(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender", (ChannelHandler)(new MessageSerializer2())).addLast((String)"encoder", (ChannelHandler)(new MessageSerializer(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler", (ChannelHandler)networkmanager);
}
})).channel(oclass)).connect(p_181124_0_, p_181124_1_).syncUninterruptibly();
return networkmanager;
}
NetworkManager.java 文件源码
项目:BaseClient
阅读 36
收藏 0
点赞 0
评论 0
public static NetworkManager func_181124_a(InetAddress p_181124_0_, int p_181124_1_, boolean p_181124_2_)
{
final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
Class <? extends SocketChannel > oclass;
LazyLoadBase <? extends EventLoopGroup > lazyloadbase;
if (Epoll.isAvailable() && p_181124_2_)
{
oclass = EpollSocketChannel.class;
lazyloadbase = field_181125_e;
}
else
{
oclass = NioSocketChannel.class;
lazyloadbase = CLIENT_NIO_EVENTLOOP;
}
((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer<Channel>()
{
protected void initChannel(Channel p_initChannel_1_) throws Exception
{
try
{
p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true));
}
catch (ChannelException var3)
{
;
}
p_initChannel_1_.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter", (ChannelHandler)(new MessageDeserializer2())).addLast((String)"decoder", (ChannelHandler)(new MessageDeserializer(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender", (ChannelHandler)(new MessageSerializer2())).addLast((String)"encoder", (ChannelHandler)(new MessageSerializer(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler", (ChannelHandler)networkmanager);
}
})).channel(oclass)).connect(p_181124_0_, p_181124_1_).syncUninterruptibly();
return networkmanager;
}
OAuthNetworkManager.java 文件源码
项目:EMC
阅读 37
收藏 0
点赞 0
评论 0
public static OAuthNetworkManager createNetworkManagerAndConnect(InetAddress address, int serverPort,
boolean useNativeTransport, OAuthCallback callback) {
final OAuthNetworkManager networkmanager = new OAuthNetworkManager(EnumPacketDirection.CLIENTBOUND, callback);
Class<? extends SocketChannel> oclass;
LazyLoadBase<? extends EventLoopGroup> lazyloadbase;
if (Epoll.isAvailable() && useNativeTransport) {
oclass = EpollSocketChannel.class;
lazyloadbase = CLIENT_EPOLL_EVENTLOOP;
} else {
oclass = NioSocketChannel.class;
lazyloadbase = CLIENT_NIO_EVENTLOOP;
}
(new Bootstrap()).group(lazyloadbase.getValue()).handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel p_initChannel_1_) throws Exception {
try {
p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true));
} catch (ChannelException var3) {
;
}
p_initChannel_1_.pipeline().addLast("timeout", new ReadTimeoutHandler(30))
.addLast("splitter", new NettyVarint21FrameDecoder())
.addLast("decoder", new NettyPacketDecoder(EnumPacketDirection.CLIENTBOUND))
.addLast("prepender", new NettyVarint21FrameEncoder())
.addLast("encoder", new NettyPacketEncoder(EnumPacketDirection.SERVERBOUND))
.addLast("packet_handler", networkmanager);
}
}).channel(oclass).connect(address, serverPort).syncUninterruptibly();
return networkmanager;
}
NetworkManager.java 文件源码
项目:Backmemed
阅读 36
收藏 0
点赞 0
评论 0
/**
* Create a new NetworkManager from the server host and connect it to the server
*/
public static NetworkManager createNetworkManagerAndConnect(InetAddress address, int serverPort, boolean useNativeTransport)
{
final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
Class <? extends SocketChannel > oclass;
LazyLoadBase <? extends EventLoopGroup > lazyloadbase;
if (Epoll.isAvailable() && useNativeTransport)
{
oclass = EpollSocketChannel.class;
lazyloadbase = CLIENT_EPOLL_EVENTLOOP;
}
else
{
oclass = NioSocketChannel.class;
lazyloadbase = CLIENT_NIO_EVENTLOOP;
}
((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer<Channel>()
{
protected void initChannel(Channel p_initChannel_1_) throws Exception
{
try
{
p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true));
}
catch (ChannelException var3)
{
;
}
p_initChannel_1_.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter", (ChannelHandler)(new NettyVarint21FrameDecoder())).addLast((String)"decoder", (ChannelHandler)(new NettyPacketDecoder(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender", (ChannelHandler)(new NettyVarint21FrameEncoder())).addLast((String)"encoder", (ChannelHandler)(new NettyPacketEncoder(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler", (ChannelHandler)networkmanager);
}
})).channel(oclass)).connect(address, serverPort).syncUninterruptibly();
return networkmanager;
}
NetworkManager.java 文件源码
项目:CustomWorldGen
阅读 31
收藏 0
点赞 0
评论 0
/**
* Create a new NetworkManager from the server host and connect it to the server
*/
@SideOnly(Side.CLIENT)
public static NetworkManager createNetworkManagerAndConnect(InetAddress address, int serverPort, boolean useNativeTransport)
{
final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
Class <? extends SocketChannel > oclass;
LazyLoadBase <? extends EventLoopGroup > lazyloadbase;
if (Epoll.isAvailable() && useNativeTransport)
{
oclass = EpollSocketChannel.class;
lazyloadbase = CLIENT_EPOLL_EVENTLOOP;
}
else
{
oclass = NioSocketChannel.class;
lazyloadbase = CLIENT_NIO_EVENTLOOP;
}
((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer<Channel>()
{
protected void initChannel(Channel p_initChannel_1_) throws Exception
{
try
{
p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true));
}
catch (ChannelException var3)
{
;
}
p_initChannel_1_.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter", (ChannelHandler)(new NettyVarint21FrameDecoder())).addLast((String)"decoder", (ChannelHandler)(new NettyPacketDecoder(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender", (ChannelHandler)(new NettyVarint21FrameEncoder())).addLast((String)"encoder", (ChannelHandler)(new NettyPacketEncoder(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler", (ChannelHandler)networkmanager);
}
})).channel(oclass)).connect(address, serverPort).syncUninterruptibly();
return networkmanager;
}
ClientSocket.java 文件源码
项目:jRakNet
阅读 37
收藏 0
点赞 0
评论 0
/**
* Initializes this socket and binds its internal udp socket to a free port.
* If the socket is already initialized any invocation of this method will
* result in an IllegalStateException.
*
* @throws SocketException Thrown in case the socket could not be initialized
*/
public void initialize() throws SocketException {
if ( this.isInitialized() ) {
throw new IllegalStateException( "Cannot re-initialized ClientSocket" );
}
this.udpSocket = new Bootstrap();
this.udpSocket.group( Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup() );
this.udpSocket.channel( Epoll.isAvailable() ? EpollDatagramChannel.class : NioDatagramChannel.class );
this.udpSocket.handler( new ChannelInboundHandlerAdapter() {
@Override
public void channelRead( ChannelHandlerContext ctx, Object msg ) throws Exception {
io.netty.channel.socket.DatagramPacket packet = (io.netty.channel.socket.DatagramPacket) msg;
PacketBuffer content = new PacketBuffer( packet.content() );
InetSocketAddress sender = packet.sender();
if ( !receiveDatagram( sender, content ) ) {
// Push datagram to update queue:
handleDatagram( sender, content, System.currentTimeMillis() );
}
}
} );
try {
this.channel = this.udpSocket.bind( ThreadLocalRandom.current().nextInt( 45000, 65000 ) ).sync().channel();
} catch ( InterruptedException e ) {
SocketException exception = new SocketException( "Could not bind to socket" );
exception.initCause( e );
throw exception;
}
this.afterInitialize();
}
ClientContext.java 文件源码
项目:Okra-Ax
阅读 35
收藏 0
点赞 0
评论 0
public void initialize(String host, int port) {
this.host = host;
this.port = port;
//
bootstrap = new Bootstrap();
if (Epoll.isAvailable()) {
this.childGroup = new EpollEventLoopGroup(cThreadCount);
this.bootstrap.group(childGroup).channel(EpollSocketChannel.class);
} else {
this.childGroup = new NioEventLoopGroup(cThreadCount);
this.bootstrap.group(childGroup).channel(NioSocketChannel.class);
}
// handlers
this.prepender = new LengthFieldPrepender(this.lengthFieldLength, false);
bootstrap.handler(new ChannelInitializer() {
@Override
protected void initChannel(Channel ch) throws Exception {
ClientContext.this.initChannel(ch);
}
});
//
this.defaultOptions();
if (!options.isEmpty()) {
for (Map.Entry<ChannelOption<Object>, Object> entry : options.entrySet()) {
bootstrap.option(entry.getKey(), entry.getValue());
}
}
}
ServerContext.java 文件源码
项目:Okra-Ax
阅读 24
收藏 0
点赞 0
评论 0
/**
* 初始化
*
* @param pThreadCount parent thread count.
* @param cThreadCount worker thread count.
* @param options netty network options。
*/
public void initialize(int pThreadCount, int cThreadCount,
Map<ChannelOption<Object>, Object> options) {
this.bootstrap = new ServerBootstrap();
if (Epoll.isAvailable()) {
this.parentGroup = new EpollEventLoopGroup(pThreadCount);
this.childGroup = new EpollEventLoopGroup(cThreadCount);
this.bootstrap.group(parentGroup, childGroup).channel(EpollServerSocketChannel.class);
} else {
this.parentGroup = new NioEventLoopGroup(pThreadCount);
this.childGroup = new NioEventLoopGroup(cThreadCount);
this.bootstrap.group(parentGroup, childGroup).channel(NioServerSocketChannel.class);
}
// handlers
this.prepender = new LengthFieldPrepender(this.lengthFieldLength, false);
bootstrap.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(Channel ch) throws Exception {
ServerContext.this.initChannel(ch);
}
});
//
this.defaultOptions();
if (!options.isEmpty()) {
for (Map.Entry<ChannelOption<Object>, Object> entry : options.entrySet()) {
bootstrap.childOption(entry.getKey(), entry.getValue());
}
}
}
Server.java 文件源码
项目:restnext
阅读 34
收藏 0
点赞 0
评论 0
/**
* Starts the server.
*/
public void start() {
loadAndPrintBanner();
try {
InetSocketAddress bindAddress = serverInitializer.getBindAddress();
ServerBootstrap serverBootstrap = Epoll.isAvailable()
? newEpoolServerBootstrap()
: newNioServerBootstrap();
ChannelFuture channelFuture = serverBootstrap
//.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(serverInitializer)
.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.bind(bindAddress)
.sync();
LOGGER.info("Application is running at - {}://{}",
(serverInitializer.isSslConfigured() ? "https" : "http"), bindAddress);
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
throw new ServerException("Could not start the server", e);
} finally {
stop();
}
}
EventLoopUtil.java 文件源码
项目:incubator-pulsar
阅读 32
收藏 0
点赞 0
评论 0
/**
* @return an EventLoopGroup suitable for the current platform
*/
public static EventLoopGroup newEventLoopGroup(int nThreads, ThreadFactory threadFactory) {
if (Epoll.isAvailable()) {
return new EpollEventLoopGroup(nThreads, threadFactory);
} else {
// Fallback to NIO
return new NioEventLoopGroup(nThreads, threadFactory);
}
}
NettyTransport.java 文件源码
项目:async-gamequery-lib
阅读 29
收藏 0
点赞 0
评论 0
/**
* <p>A factory method that manufactures {@link EventLoopGroup} based on {@link ChannelType}. If the platform
* supports
* Epoll and the channel type is NIO, it will return {@link EpollEventLoopGroup} instead.</p>
*
* @param type
* The {@link ChannelType} that will determine which {@link EventLoopGroup} will be returned.
*
* @return The concrete {@link EventLoopGroup} instance that will be used by the transport.
*/
private EventLoopGroup createEventLoopGroup(ChannelType type) {
switch (type) {
case NIO_TCP:
case NIO_UDP:
if (Epoll.isAvailable()) {
log.debug("Using EpollEventLoopGroup");
return new EpollEventLoopGroup(8, executorService, DefaultSelectStrategyFactory.INSTANCE);
}
return new NioEventLoopGroup(8, executorService, SelectorProvider.provider(), DefaultSelectStrategyFactory.INSTANCE);
}
return null;
}
NettyNetworkingClient.java 文件源码
项目:Coerce
阅读 43
收藏 0
点赞 0
评论 0
@Override
public void configure(NetworkChannelHandler handler) {
this.handler = handler;
final boolean useEpoll = Epoll.isAvailable() && this.configuration.getBoolean("epoll");
this.eventLoopGroup = useEpoll ? new EpollEventLoopGroup(this.configuration.getInt("threads")) :
new NioEventLoopGroup(this.configuration.getInt("threads"));
bootstrap.group(this.eventLoopGroup);
bootstrap.channel(useEpoll ? EpollSocketChannel.class : NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.option(ChannelOption.TCP_NODELAY, true);
}
ServerBootstrapFactory.java 文件源码
项目:hackathon-2015
阅读 25
收藏 0
点赞 0
评论 0
public ServerBootstrap newServerBootstrap(int acceptor, int ioThread) throws IllegalArgumentException {
if (acceptor < 0 || ioThread < 0) {
throw new IllegalArgumentException("acceptor/ioThread number < 0");
}
if (Epoll.isAvailable()) {
logger.info("Platform is {}, use EpollEventLoopGroup", System.getProperties().getProperty("os.name"));
return newEpollServerBootstrap(acceptor, ioThread);
}
logger.info("Platform is {}, use NioEventLoopGroup", System.getProperties().getProperty("os.name"));
return newNioServerBootstrap(acceptor, ioThread);
}
BaseRedissonSessionManager.java 文件源码
项目:redis-session-manager
阅读 21
收藏 0
点赞 0
评论 0
/**
* Determine if native Epoll for netty is available
* @return
*/
protected boolean isEpollSupported() {
final boolean available = Epoll.isAvailable();
if (available) {
log.info("Using native epoll");
}
return available;
}
HttpServer.java 文件源码
项目:netty-rest
阅读 33
收藏 0
点赞 0
评论 0
HttpServer(Set<HttpService> httpServicePlugins,
Set<WebSocketService> websocketServices,
Swagger swagger, EventLoopGroup eventLoopGroup,
List<PreprocessorEntry> preProcessors,
ImmutableList<PostProcessorEntry> postProcessors,
ObjectMapper mapper,
Map<Class, PrimitiveType> overriddenMappings,
HttpServerBuilder.ExceptionHandler exceptionHandler,
Map<String, IRequestParameterFactory> customParameters,
BiConsumer<Method, Operation> swaggerOperationConsumer,
boolean useEpoll,
boolean proxyProtocol,
long maximumBodySize)
{
this.routeMatcher = new RouteMatcher();
this.preProcessors = preProcessors;
this.workerGroup = requireNonNull(eventLoopGroup, "eventLoopGroup is null");
this.swagger = requireNonNull(swagger, "swagger is null");
this.mapper = mapper;
this.customParameters = customParameters;
this.swaggerOperationConsumer = swaggerOperationConsumer;
this.uncaughtExceptionHandler = exceptionHandler == null ? (t, e) -> {
} : exceptionHandler;
this.postProcessors = postProcessors;
this.proxyProtocol = proxyProtocol;
this.maximumBodySize = maximumBodySize;
this.bossGroup = useEpoll ? new EpollEventLoopGroup(1) : new NioEventLoopGroup(1);
registerEndPoints(requireNonNull(httpServicePlugins, "httpServices is null"), overriddenMappings);
registerWebSocketPaths(requireNonNull(websocketServices, "webSocketServices is null"));
routeMatcher.add(GET, "/api/swagger.json", this::swaggerApiHandle);
this.useEpoll = useEpoll && Epoll.isAvailable();
this.processingRequests = new ConcurrentHashMap<>();
}
HttpServerBuilder.java 文件源码
项目:netty-rest
阅读 25
收藏 0
点赞 0
评论 0
public HttpServer build()
{
if (eventLoopGroup == null) {
eventLoopGroup = useEpoll ? new EpollEventLoopGroup() : new NioEventLoopGroup();
}
if (swagger == null) {
swagger = new Swagger();
}
if (websocketServices == null) {
websocketServices = ImmutableSet.of();
}
if (customRequestParameters == null) {
customRequestParameters = ImmutableMap.of();
}
return new HttpServer(
httpServices,
websocketServices,
swagger,
eventLoopGroup,
jsonRequestPreprocessors.build(),
postProcessorEntryBuilder.build(),
mapper == null ? HttpServer.DEFAULT_MAPPER : mapper,
overridenMappings,
exceptionHandler,
customRequestParameters,
swaggerOperationConsumer,
useEpoll && Epoll.isAvailable(),
proxyProtocol, maximumBodySize);
}