将windows套接字转换为.net

本文关键字:net 转换 套接字 windows | 更新日期: 2023-09-27 18:10:08

我有一个非常简单的套接字连接,似乎在WinSock 2.0下工作,但在。net下根本不起作用。我唯一知道的是一个工作,另一个不工作,但我不知道如何调试它。

Windows sockets版本:

INT_PTR CALLBACK ConnectDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    SOCKET ConnectMe;
    int Status, cRemoteAddr;
    LRESULT ItemData;
    SOCKADDR_IN SockAddr, RemoteAddr;
    CERDISPINFO Info;
    BOOL fReuseAddr = TRUE;
    switch (uMsg) {
    case WM_INITDIALOG :
        memset (&SockAddr, 0, sizeof(SockAddr));
        SockAddr.sin_family = AF_INET;
        SockAddr.sin_port = htons(987);
        SockAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
        ConnectMe = socket (AF_INET, SOCK_DGRAM, 0);
        setsockopt (ConnectMe, SOL_SOCKET, SO_REUSEADDR, (char *)&fReuseAddr, sizeof(fReuseAddr));
        bind (ConnectMe, (SOCKADDR *)&SockAddr, sizeof(SockAddr));
        WSAAsyncSelect (ConnectMe, hwndDlg, WM_CONNECT_ME, FD_READ);
        SetWindowLong (hwndDlg, GWL_USERDATA, (LONG)ConnectMe);
        return TRUE;
    case WM_CONNECT_ME :
        ConnectMe = (SOCKET)wParam;
        cRemoteAddr = sizeof(RemoteAddr);
        Status = recvfrom (ConnectMe, (char*)&Info, sizeof(Info), 0, (SOCKADDR*)&RemoteAddr, &cRemoteAddr);
        if (Status != SOCKET_ERROR)
                {
            // Convert ip addr to host order
            ItemData = ntohl(RemoteAddr.sin_addr.S_un.S_addr);
        }
        return TRUE;
    }
    return FALSE;
}

下面是大致等价的。net版本:

public Form1()
{
    InitializeComponent();
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Unspecified);
    SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
    socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(socketEventArg_Completed);
    socketEventArg.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 987);
    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    socket.Bind(new IPEndPoint(IPAddress.Any, 987));
    socket.ConnectAsync(socketEventArg);
}
void socketEventArg_Completed(Object sender, SocketAsyncEventArgs e)
{
    Boolean b = true;
}

. net版本永远不会碰到'Boolean b = true'断点,而c++ WinSocks会在一秒左右的时间内报告有一个设备,每次。我甚至尝试在。net版本中将端口中的字节顺序反转到56067,但它也不起作用。我错过了什么?看起来。net不接受0.0.0.0的远程端点…

将windows套接字转换为.net

问题解决了:

Form1()
{
    UdpClient client = new UdpClient(987);
    client.BeginReceive(UDPClient_Callback, client);
}
void UDPClient_Callback(IAsyncResult result)
{
}

感谢大家的关注!