Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The <code>Socket</code> class has the <code>Handle</code> property, which could be used.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.handle.aspx" rel="noreferrer">Socket.Handle @ MSDN</a></p> <p>I was skeptical about whether this would work, but I was able to get it to work with no fuss at all.</p> <p>To start, I made an unmanaged C++ dll to export a single function that can do something with a socket. Here's the function I created.</p> <pre><code>#include &lt;WinSock.h&gt; // This is an example of an exported function. extern "C" __declspec(dllexport) void __stdcall DoStuffWithSocket(DWORD sock) { const char *data = "woot\r\n"; send((SOCKET)sock, data, strlen(data), 0); } </code></pre> <p>The project outputs a dll named <code>UnmanagedSocketHandler.dll</code>, which is the library mentioned in the P/Invoke signature in the next snippet.</p> <p>Here's a quick and dirty C# console app to call that function as a Server.</p> <pre><code>using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; namespace SocketHandleShareTest { class Program { static void Main(string[] args) { IPEndPoint ep = new IPEndPoint(IPAddress.Any, 5353); Socket sListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sListen.Bind(ep); sListen.Listen(10); Socket sClient = sListen.Accept(); Console.WriteLine("DoStuffWithSocket() enter"); Console.ReadLine(); DoStuffWithSocket(sClient.Handle); Console.WriteLine("DoStuffWithSocket() exit"); Console.ReadLine(); sClient.Close(); sListen.Close(); Console.WriteLine("Done."); Console.ReadLine(); } [DllImport("UnmanagedSocketHandler.dll")] static extern void DoStuffWithSocket(IntPtr sock); } } </code></pre> <p>Last, a quick and dirty C# client app to talk to the server. I was unable to find any documentation on why this works, but it works. I'd be wary about what you try to do with the socket.</p> <pre><code>using System.Net; using System.Net.Sockets; namespace SocketHandleShareTestClient { class Program { static void Main(string[] args) { byte[] buf = new byte[40]; Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); s.Connect("localhost", 5353); int len = s.Receive(buf); Console.WriteLine("{0} bytes read.", len); if (len &gt; 0) { string data = Encoding.ASCII.GetString(buf, 0, len); Console.WriteLine(data); } s.Close(); Console.ReadLine(); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload