The purpose to duplicate the socket by calling the DuplicateAndClose method is to accept the socket in main AppDomain but to process it in a separated AppDomain so the process logic can be unloaded & updated without restarting the process.
Currently all the logic happened in the same AppDomain and the major problem is that after I invoke method DuplicateAndClose and create a new socket based on the SocketInformation, that socket always receive 0 length data.
Does any one know what is the correct step to use the DuplicateAndClose method and receive data from the duplicated socket? Thanks.
Listening on port and accept socket
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();
Duplicate socket and receive data
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);
}