c#中的异步广播客户端

本文关键字:广播 客户端 异步 | 更新日期: 2023-09-27 18:12:18

任何帮助/反馈将不胜感激。我正在开发一个广播客户端接收器,以便它接收来自服务器的数据。客户端异步发送和接收数据。换句话说,我利用了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);
    }
}  

c#中的异步广播客户端

你得到错误,因为你是混合TCP和UDP。

EndReceive用于基于连接的协议。RemoteEndPoint属性也是如此。

您应该调用EndReceiveFrom,它也返回远程端点