Class: Kcp::Engine

Inherits:
Object
  • Object
show all
Defined in:
lib/kcp.rb

Overview

可靠字节流引擎(stream 模式)。它只负责「把一段字节流可靠送达对端」, 不处理网络 I/O、地址、加密 —— 这些由调用方负责。

用法: engine = Kcp::Engine.new(conv) engine.send(data) # 把数据排队 engine.flush # 立即刷出(生成 KCP 包) pkt = engine.output # 取出待发送的编码包,交给 UDP sendto engine.input(recv_pkt) # 喂入收到的编码包 chunk = engine.recv # 取出对端送来的可靠字节流 engine.update(now_ms) # 周期性驱动(重传/窗口更新)

Instance Method Summary collapse

Constructor Details

#initialize(conv) ⇒ Engine

conv 是会话标识(uint32),连接两端必须一致。



23
24
25
# File 'lib/kcp.rb', line 23

def initialize(conv)
  @ctx = KcpNative.kcp_new(conv)
end

Instance Method Details

#closeObject

释放引用(C 对象由 GC 回收)。



79
80
81
# File 'lib/kcp.rb', line 79

def close
  @ctx = nil
end

#flushObject

立即刷出待发送数据(不受 update 的间隔节流)。



51
52
53
# File 'lib/kcp.rb', line 51

def flush
  KcpNative.kcp_flush(@ctx)
end

#input(data) ⇒ Object

喂入一个收到的 KCP 编码包(低层 UDP 数据报的内容)。



40
41
42
# File 'lib/kcp.rb', line 40

def input(data)
  KcpNative.kcp_input(@ctx, data)
end

#mssObject

当前分段载荷大小(= mtu - 24 字节 KCP 头)。单次 send 最多接受 IKCP_WND_RCV(128) 个分段,超出会返回 -2 丢弃;上层按 mss 切块可避免。



64
65
66
# File 'lib/kcp.rb', line 64

def mss
  KcpNative.kcp_mss(@ctx)
end

#outputObject

取出待发送的编码包(一次一个 KCP 包),交给低层发送。没有待发送时返回 nil。



69
70
71
# File 'lib/kcp.rb', line 69

def output
  KcpNative.kcp_output(@ctx)
end

#recv(maxlen = 65_536) ⇒ Object

取出对端已送达的、按序的字节流(最多 maxlen 字节)。 没有数据时返回 nil。



35
36
37
# File 'lib/kcp.rb', line 35

def recv(maxlen = 65_536)
  KcpNative.kcp_recv(@ctx, maxlen)
end

#send(data) ⇒ Object

把数据排队等待可靠发送。返回排入的字节数,出错返回负数。 注意:数据不会立即发出去,需要调用 #flush(或 #update)刷出。



29
30
31
# File 'lib/kcp.rb', line 29

def send(data)
  KcpNative.kcp_send(@ctx, data)
end

#setmtu(mtu) ⇒ Object

设置 KCP 包的最大尺寸(mtu)。默认 1300。上层(如 mnet)把每个 KCP 包 再包一层头作为单个 UDP 数据报发送时,应把它设成「链路 MTU - 上层头开销」, 否则整包会超过 MTU 触发 IP 分片。



58
59
60
# File 'lib/kcp.rb', line 58

def setmtu(mtu)
  KcpNative.kcp_setmtu(@ctx, mtu)
end

#update(now_ms) ⇒ Object

驱动 KCP 时钟(按间隔触发的重传、ACK、窗口探测)。now_ms 是毫秒时间戳, 内部会截断到 32 位(KCP 用 uint32 毫秒,约 49 天回绕一次,属正常)。



46
47
48
# File 'lib/kcp.rb', line 46

def update(now_ms)
  KcpNative.kcp_update(@ctx, now_ms.to_i & 0xffffffff)
end

#waitsndObject

发送队列里待发送的包数(>0 表示窗口已满、有积压)。



74
75
76
# File 'lib/kcp.rb', line 74

def waitsnd
  KcpNative.kcp_waitsnd(@ctx)
end