KcpServer.java 2.36 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package emu.grasscutter.netty;

import java.net.InetSocketAddress;

import emu.grasscutter.Grasscutter;
import io.jpower.kcp.netty.ChannelOptionHelper;
import io.jpower.kcp.netty.UkcpChannelOption;
import io.jpower.kcp.netty.UkcpServerChannel;
import io.netty.bootstrap.UkcpServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;

@SuppressWarnings("rawtypes")
16
public class KcpServer extends Thread {
Melledy's avatar
Melledy committed
17
18
19
20
21
22
	private EventLoopGroup group;
	private UkcpServerBootstrap bootstrap;
	
	private ChannelInitializer serverInitializer;
	private InetSocketAddress address;
	 
23
	public KcpServer(InetSocketAddress address) {
Melledy's avatar
Melledy committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    	this.address = address;
    	this.setName("Netty Server Thread");
    }
	
	public InetSocketAddress getAddress() {
    	return this.address;
    }

    public ChannelInitializer getServerInitializer() {
		return serverInitializer;
	}

	public void setServerInitializer(ChannelInitializer serverInitializer) {
		this.serverInitializer = serverInitializer;
	}

	@Override
	public void run() {
		if (getServerInitializer() == null) {
43
			this.setServerInitializer(new KcpServerInitializer());
Melledy's avatar
Melledy committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
		}
		
        try {
        	group = new NioEventLoopGroup();
            bootstrap = new UkcpServerBootstrap();
            bootstrap.group(group)
                    .channel(UkcpServerChannel.class)
                    .childHandler(this.getServerInitializer());
            ChannelOptionHelper
            	.nodelay(bootstrap, true, 20, 2, true)
            	.childOption(UkcpChannelOption.UKCP_MTU, 1200);
            
            // Start handler
            this.onStart();
            
            // Start the server.
            ChannelFuture f = bootstrap.bind(getAddress()).sync();
            
            // Start finish handler
            this.onStartFinish();

            // Wait until the server socket is closed.
            f.channel().closeFuture().sync();
67
68
        } catch (Exception exception) {
			Grasscutter.getLogger().error("Unable to start game server.", exception);
Melledy's avatar
Melledy committed
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
		} finally {
        	// Close
			finish();
        }
	}
	
	public void onStart() {

	}

	public void onStartFinish() {

	}
	
	private void finish() {
		try {
			group.shutdownGracefully();
		} catch (Exception e) {
			
		}
		Grasscutter.getLogger().info("Game Server closed");
	}
}