c#中的异步广播客户端

时间:2011-10-24 13:32:12

标签: c# sockets network-programming client-server

任何帮助/反馈将不胜感激。我正在开发一个广播客户端接收器,以便它接收来自服务器的数据。客户端异步发送和接收数据。换句话说,我使用socket.BeginReceiveFrom()和socket.BeginSendTo()等方法 但是,我想以某种方式得到服务器的IP地址,但当我使用RemoteEndPoint()方法获取服务器的IP地址时,我得到错误。部分代码如下所示。

private void Form1_Load(object sender, EventArgs e) {
    byteData = msgToSend.ToByte();

    clientSocket.BeginSendTo(byteData, 0, byteData.Length, SocketFlags.None, epServer, new AsyncCallback(OnSend), null);

    byteData = new byte[1024];
    //Start listening to the data asynchronously
    clientSocket.BeginReceiveFrom (byteData,0, byteData.Length,SocketFlags.None,ref epServer,new AsyncCallback(OnReceive),null);
}

private void OnReceive(IAsyncResult ar) {            
    try {                
        clientSocket.EndReceive(ar);
        byteData = new byte[1024];

        // HERE MY CODE TO FIND THE IP ADDRESS OF THE SERVER
        IPEndPoint ip = (IPEndPoint)epServer.RemoteEndPoint;
        MessageBox.Show(Convert.ToString(ip.Address));

        //Start listening to receive more data from the user
        clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length,             SocketFlags.None, ref epServer,new AsyncCallback(OnReceive), null);
    } catch (ObjectDisposedException) { 

    } catch (Exception ex) {
        MessageBox.Show(ex.Message, "SGSclient: " + strName, MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}  

1 个答案:

答案 0 :(得分:0)

由于您正在混合TCP和UDP,因此收到错误。

EndReceive用于基于连接的协议。与RemoteEndPoint属性一样。

您应该调用EndReceiveFrom并返回远程终点