RuneHive-Tarnish
Neural OSRS Enhancement Framework
Loading...
Searching...
No Matches
NetworkService.java
1package com.osroyale.game.service;
2
3import com.osroyale.Config;
4import com.osroyale.OSRoyale;
5import com.osroyale.net.ServerPipelineInitializer;
6import io.netty.bootstrap.ServerBootstrap;
7import io.netty.buffer.PooledByteBufAllocator;
8import io.netty.channel.ChannelFuture;
9import io.netty.channel.ChannelOption;
10import io.netty.channel.EventLoopGroup;
11import io.netty.channel.WriteBufferWaterMark;
12import io.netty.channel.epoll.Epoll;
13import io.netty.channel.epoll.EpollEventLoopGroup;
14import io.netty.channel.epoll.EpollServerSocketChannel;
15import io.netty.channel.nio.NioEventLoopGroup;
16import io.netty.channel.socket.nio.NioServerSocketChannel;
17import io.netty.util.ResourceLeakDetector;
18import org.apache.logging.log4j.LogManager;
19import org.apache.logging.log4j.Logger;
20
21import java.util.concurrent.TimeUnit;
22
52
53public final class NetworkService {
54
55 private static final Logger logger = LogManager.getLogger(NetworkService.class);
56
57 public void start(int port) throws Exception {
58 logger.info("Starting network service on port: " + port);
59
60 ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED);
61 final EventLoopGroup bossGroup = Epoll.isAvailable() ? new EpollEventLoopGroup(1) : new NioEventLoopGroup(1);
62 final EventLoopGroup workerGroup = Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup();
63
64 try {
65 ServerBootstrap b = new ServerBootstrap();
66 b.group(bossGroup, workerGroup)
67 .channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
68 .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
69 .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
70 .childOption(ChannelOption.TCP_NODELAY, true)
71 .childOption(ChannelOption.AUTO_READ, true)
72 .childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(2 << 16, 2 << 18))
73 .childOption(ChannelOption.SO_SNDBUF, 65536)
74 .childOption(ChannelOption.SO_RCVBUF, 65536)
75 .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30_000)
76 .childOption(ChannelOption.IP_TOS, Config.IP_TOS)
77 .childHandler(new ServerPipelineInitializer());
78
79 ChannelFuture f = b.bind(port).syncUninterruptibly();
80
81 OSRoyale.serverStarted.set(true);
82
83 logger.info(String.format("Server built successfully (took %d seconds).", OSRoyale.UPTIME.elapsedTime(TimeUnit.SECONDS)));
84 OSRoyale.UPTIME.reset();
85 f.channel().closeFuture().sync();
86 } catch (Exception ex) {
87 logger.error("error starting network service.", ex);
88 } finally {
89 bossGroup.shutdownGracefully();
90 workerGroup.shutdownGracefully();
91 }
92 }
93
94}