如何实现简单UDP和SNI代理的done状态?
摘要:由于之前借鉴 Kestrel 了非常多抽象和优化实现,对于后续的扩展非常便利, 实现 简单udp和sni 代理 两个功能比预期快了超多(当然也有偷懒因素) (PS 大家有空的话,能否在 GitHub https:github.comf
由于之前借鉴 Kestrel 了非常多抽象和优化实现,对于后续的扩展非常便利,
实现 简单udp和sni 代理 两个功能比预期快了超多(当然也有偷懒因素)
(PS 大家有空的话,能否在 GitHub https://github.com/fs7744/NZOrz 点个 star 呢?毕竟借鉴代码也不易呀 哈哈哈哈哈)
简单udp代理
这里的udp 代理功能比较简单:代理程序收到任何 udp 包都会通过路由匹配找 upstream ,然后转发给upstream
udp proxy 使用配置
基本格式和之前 tcp proxy 一致,
只是Protocols得选择UDP, 然后多了UdpResponses 允许 upstream 返回多少个 udp 包给请求者, 默认为0,即不返回任何包
{
"Logging": {
"LogLevel": {
"Default": "Information"
}
},
"ReverseProxy": {
"Routes": {
"udpTest": {
"Protocols": [ "UDP" ],
"Match": {
"Hosts": [ "*:5000" ]
},
"ClusterId": "udpTest",
"RetryCount": 1,
"UdpResponses": 1,
"Timeout": "00:00:11"
}
},
"Clusters": {
"udpTest": {
"LoadBalancingPolicy": "RoundRobin",
"HealthCheck": {
"Passive": {
"Enable": true
}
},
"Destinations": [
{
"Address": "127.0.0.1:11000"
}
]
}
}
}
}
实现
这里列举一下,表明有多简单
ps: 由于要实现的是非常简单udp代理,所以不基于IMultiplexedConnectionListener ,而基于 IConnectionListener 方式 (对,就是俺偷懒了)
1. 实现 UdpConnectionContext
偷懒就直接把udp 包数据放 context 上了,不放 Parameters 上,减少字典实例和内存使用
public sealed class UdpConnectionContext : TransportConnection
{
private readonly IMemoryOwner<byte> memory;
public Socket Socket { get; }
public int ReceivedBytesCount { get; }
public Memory<byte> ReceivedBytes => memory.Memory.Slice(0, ReceivedBytesCount);
public UdpConnectionContext(Socket socket, UdpReceiveFromResult result)
{
Socket = socket;
ReceivedBytesCount = result.ReceivedBytesCount;
this.memory = result.Buffer;
LocalEndPoint = socket.LocalEndPoint;
RemoteEndPoint = result.RemoteEndPoint;
}
public UdpConnectionContext(Socket socket, EndPoint remoteEndPoint, int receivedBytes, IMemoryOwner<byte> memory)
{
Socket = socket;
ReceivedBytesCount = receivedBytes;
