你不能这样做,因为 Socket 类创建和管理它自己的私有套接字句柄。从理论上讲,您可以使用一些邪恶的反射将您的套接字句柄塞入 Socket 的私有字段中,但那完全是 hack,我不会这样做。
给定一个有效的套接字句柄,您可以通过 P/Invoke 调用 Win32 recv 函数来接收数据,如下所示:
[DllImport("ws2_32.dll")]
extern static int recv([In] IntPtr socketHandle, [In] IntPtr buffer,
[In] int count, [In] SocketFlags socketFlags);
/// <summary>
/// Receives data from a socket.
/// </summary>
/// <param name="socketHandle">The socket handle.</param>
/// <param name="buffer">The buffer to receive.</param>
/// <param name="offset">The offset within the buffer.</param>
/// <param name="size">The number of bytes to receive.</param>
/// <param name="socketFlags">The socket flags.</param>
/// <exception cref="ArgumentException">If <paramref name="socketHandle"/>
/// is zero.</exception>
/// <exception cref="ArgumentNullException">If <paramref name="buffer"/>
/// is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">If the
/// <paramref name="offset"/> and <paramref name="size"/> specify a range
/// outside the given buffer.</exception>
public static int Receive(IntPtr socketHandle, byte[] buffer, int offset,
int size, SocketFlags socketFlags)
{
if (socketHandle == IntPtr.Zero)
throw new ArgumentException("socket");
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0 || offset >= buffer.Length)
throw new ArgumentOutOfRangeException("offset");
if (size < 0 || offset + size > buffer.Length)
throw new ArgumentOutOfRangeException("size");
unsafe
{
fixed (byte* pData = buffer)
{
return Recv(socketHandle, new IntPtr(pData + offset),
size, socketFlags);
}
}
}