2011-10-20 113 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();