shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
1
2
3
4
5
6
7
8
9
10
11
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
package com.walker.tcp.netty;
 
import com.walker.tcp.Response;
import com.walker.tcp.connect.LongConnection;
import io.netty.channel.ChannelHandlerContext;
 
/**
 * 由netty底层实现的长连接对象,该连接被抽象为一个长的TCP连接句柄。
 * @author 时克英
 *
 */
public class DefaultLongConnection extends LongConnection {
 
    public ChannelHandlerContext ctx;
 
    public DefaultLongConnection(String id){
        super(id);
    }
 
    public DefaultLongConnection(String id, ChannelHandlerContext ctx){
        super(id);
        if(ctx == null){
            throw new IllegalArgumentException("构造'DefaultLongConnection'失败,缺少构造参数:ChannelHandlerContext");
        }
        this.ctx = ctx;
    }
 
    @Override
    public void write(Response<?> response) {
        super.write(response);
        this.ctx.writeAndFlush(response.toData());
    }
 
    @Override
    public void disconnect() {
//        ChannelFuture result = this.ctx.close();
         this.ctx.close();
    }
 
    @Override
    public boolean isConnected() {
        return ctx.channel().isOpen();
    }
 
    public void setChannelHandlerContext(ChannelHandlerContext ctx){
        this.ctx = ctx;
    }
}