2011-10-24 118 views
0

任何幫助/反饋將不勝感激。我正在開發一個廣播客戶端接收器,以便它接收來自服務器的數據。客戶端異步地發送和接收數據。換句話說,我使用的方法,如socket.BeginReceiveFrom()和socket.BeginSendTo() 然而,我想以某種方式獲得服務器的IP地址,但是當我使用方法RemoteEndPoint()獲取IP服務器地址我得到錯誤。部分代碼如下所示。c#中的異步廣播客戶端#

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); 
    } 
} 
+3

**您得到了什麼錯誤**? – SLaks

+1

我相信這是你以前的問題的擴展:http://stackoverflow.com/questions/7842443/asynchronous-client-broadcast-receiver/7853129#7853129我在那裏提供的答案應該允許你得到服務器的IP – robowahoo

+0

Thx robowahoo,我剛剛在鏈接中顯示的代碼中看到了我的錯誤。而不是EndReceived()方法,我使用EndReceiveFrom()返回結束點。 –

回答

0

因爲您正在混合TCP和UDP,所以出現錯誤。

EndReceive用於基於連接的協議。同RemoteEndPoint屬性一樣。

您應該調用EndReceiveFrom,這也會返回遠程終點