5

我想将 message.WParam 转换为 Socket。

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == Values.MESSAGE_ASYNC)
        {

            switch (m.LParam.ToInt32())
            {
                case Values.FD_READ:
                    WS2.Receive(m.WParam);
                case Values.FD_WRITE: break;
                default: break;
            }

        }
        else
        {
            base.WndProc(ref m);
        }
    }

public class WS2
{
    public static void Receive(IntPtr sock)
    {
        Socket socket = sock;
    }
}

如何将 IntrPtr(sock) 转换为 Socket,以便调用 Receive()?

4

2 回答 2

6

你不能这样做,因为 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);
    }
  }
}
于 2009-04-19T14:10:02.490 回答
1

Socket 类中没有任何内容可以执行此操作 - 尽管它使用底层句柄,但没有 API 来操作它,并且Handle 属性是只读的。

最好只使用 P/Invoking recv并使用 IntPtr 句柄直接调用它。

快速浏览一下Rotor 代码,您可以轻松创建一个Socket,关闭它的handle,然后将它的m_handle 字段设置为您自己的。但这需要反射,并且如果您的套接字已经连接(听起来像是 - 因为您刚刚询问了调用 recv),那么您还必须操纵 Socket 的私有状态 - 这使得这个想法更加不受欢迎并且更脆弱。

于 2009-04-19T13:56:45.113 回答