2011-10-20 152 views
1

我希望對此問題提供任何幫助/反饋。我正在C#中開發一個異步套接字連接,我想設置一個廣播客戶端接收器,使其廣播本地網絡服務器,然後它從本地服務器接收消息。主要問題是首先我想從一個客戶端向不同的服務器進行廣播,然後從所有服務器中檢索IP地址。這裏是客戶端代碼的一部分。也服務器端工作正常。異步客戶端廣播接收器

public void ButtonConnectOnClick() 
    { 
     // Init socket Client 
     newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 
     newsock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); 
     IPAddress ipAddress = IPAddress.Broadcast; //Parse(txtServerIP.Text); 
     IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, BROADCASTPORT); 
     epServer = (EndPoint)ipEndPoint; 
     string tmp = "hello"; 
     byteData = Encoding.ASCII.GetBytes(tmp); 
     newsock.BeginSendTo(byteData, 0, byteData.Length, SocketFlags.None, epServer, new AsyncCallback(OnSend), null); 
     byteData = new byte[1024]; 
     newsock.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epServer, new AsyncCallback(OnReceive), null); 
    } 

    private void OnSend(IAsyncResult ar) 
    { 
     try 
     { 
      newsock.EndSend(ar); 
     } 
     catch (ObjectDisposedException) 
     { } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 
    } 

    private void OnReceive(IAsyncResult ar) 
    { 
     try 
     { 
      newsock.EndReceive(ar);    

      byteData = new byte[1024]; 

      //Start listening to receive more data from the user 
      newsock.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epServer, new AsyncCallback(OnReceive), null); 
     } 
     catch (ObjectDisposedException) 
     { } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 
    } 
+0

你見過這個網站通過'http:// meta.codereview.stackexchange.com /'? –

回答

0

一種選擇是使用現有的服務發現項目。 ZeroConf是基於Apple Bounjour的完整.NET實現。利用這個框架將允許你啓動你的應用並查詢所有可用的服務及其IP地址。

代碼是project documentation的直接副本,但發佈以顯示易用性。

發現(客戶端)

static void Main(string[] args) 
    { 
     BonjourServiceResolver bsr = new BonjourServiceResolver(); 
     bsr.ServiceFound += new Network.ZeroConf.ObjectEvent<Network.ZeroConf.IService>(bsr_ServiceFound); 
     bsr.Resolve("_daap._tcp"); 
     Console.ReadLine(); 
    } 

    static void bsr_ServiceFound(Network.ZeroConf.IService item) 
    { 
     // Here goes the code for what you want to do when a service is discovered 
     Console.WriteLine(item); 
    } 

出版(服務器端)

Service s = new Service(); 
s.AddAddress(ResolverHelper.GetEndPoint()); 
s.Protocol = "_touch-able._tcp.local."; 
s.Name = "MyName"; 
s.HostName = s.Addresses[0].DomainName; 

//The indexer on the service enables to set metadatas 
s["DvNm"] = "PC Remote"; 
s["RemV"] = "10000"; 
s["DvTy"] = "iPod"; 
s["RemN"] = "Remote"; 
s["txtvers"] = "1"; 
s["Pair"] = "0000000000000001"; 

//After setting all this, the only thing left to do is to publish your service 
s.Publish(); 
Thread.Sleep(3600000); 
s.Stop();