KcpChannel.java 2.11 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
3
4
5
6
7
8
9
10
package emu.grasscutter.netty;

import emu.grasscutter.Grasscutter;
import io.jpower.kcp.netty.UkcpChannel;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

11
public abstract class KcpChannel extends ChannelInboundHandlerAdapter {
Melledy's avatar
Melledy committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
	private UkcpChannel kcpChannel;
	private ChannelHandlerContext ctx;
	private boolean isActive;
	
    public UkcpChannel getChannel() {
		return kcpChannel;
	}
    
    public boolean isActive() {
    	return this.isActive;
    }

	@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.kcpChannel = (UkcpChannel) ctx.channel();
        this.ctx = ctx;
        this.isActive = true;
       
        this.onConnect();
    }
	
	@Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		this.isActive = false;
		
        this.onDisconnect();
    }

	@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
    	ByteBuf data = (ByteBuf) msg;
    	onMessage(ctx, data);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        close();
    }

    protected void send(byte[] data) {
    	if (!isActive()) {
    		return;
    	}
    	ByteBuf packet = Unpooled.wrappedBuffer(data);
    	kcpChannel.writeAndFlush(packet);
    }
    
    public void close() {
    	if (getChannel() != null) {
    		getChannel().close();
    	}
    }

    /*
    protected void logPacket(ByteBuffer buf) {
		ByteBuf b = Unpooled.wrappedBuffer(buf.array());
    	logPacket(b);
    } 
    */
    
    protected void logPacket(ByteBuf buf) {
    	Grasscutter.getLogger().info("Received: \n" + ByteBufUtil.prettyHexDump(buf));
    }
    
    // Events

	protected abstract void onConnect();

    protected abstract void onDisconnect();
    
    public abstract void onMessage(ChannelHandlerContext ctx, ByteBuf data);
}