通过调用DuplicateAndClose方法复制套接字的目的是接受主AppDomain中的套接字,但是要在分离的AppDomain中处理它,以便可以卸载进程逻辑&更新而不重新启动过程。
目前所有逻辑都发生在同一个AppDomain中,主要问题是在调用方法DuplicateAndClose并基于SocketInformation创建一个新套接字后,该套接字总是收到0个长度数据。
是否有人知道使用DuplicateAndClose方法并从重复套接字接收数据的正确步骤是什么?感谢。
聆听端口并接受套接字
Thread th = new Thread(new ThreadStart(() =>
{
using (var listenSocket = new Socket(afamily, stype, ptype))
{
try
{
IPEndPoint iep = new IPEndPoint(IPAddress.Any, port);
listenSocket.Bind(iep);
listenSocket.Listen(5000);
Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} listening on port {port}");
while (!isending)
{
Socket ask = null;
try
{
var handler = new DomainSocketHandler(GetType().FullName);
ask = listenSocket.Accept();
handler.Handle(ask);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
}));
th.Start();
重复套接字和接收数据
var si = accepted.DuplicateAndClose(Process.GetCurrentProcess().Id);
var info = si;
using (var psk = new Socket(info))
{
int len = 0;
var buf = new byte[4096];
while (true)
{
try
{
len = psk.Receive(buf);
if (len < 1 && psk.Available < 1)
{
break;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
string response = @"Connection:close
Content-Type:text/html; charset=utf-8
<html><body>Success</body></html>";
UTF8Encoding en = new UTF8Encoding();
var bytes = en.GetBytes(response);
psk.Send(bytes);
}