0

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);
}
Dovydas Šopa
  • 2,282
  • 8
  • 26
  • 34
Mark Yuan
  • 850
  • 1
  • 8
  • 17
  • 1
    Why is placing the listener in the remote appdomain not an option? – Damien_The_Unbeliever Jan 08 '16 at 08:32
  • It sounds like the other side has already closed their end of the socket. What does the client code look like? – Luaan Jan 08 '16 at 08:54
  • If you put listener at a remote domain, when you want to update the dll, you have to shutdown the listener within the AppDomain which will cause the port stop working for a while. This will impact the availability of the server. – mind1n Jan 08 '16 at 14:06

0 Answers0