客户端使用GenuineChannels连接到服务器(我们正在考虑切换到DotNetRemoting).我的意思是找到要连接的服务器的IP和端口号.
看起来像蛮力的方法是尝试网络上的每个IP尝试活动端口(甚至不确定是否可能)但必须有更好的方法.
考虑广播特定的UDP数据包.当服务器看到广播的UDP数据包时,它们会发送回复.客户端可以收集来自所有服务器的回复,并开始连接它们或基于选举算法.
请参阅客户端示例(未经测试的代码):
using System.Net; using System.Net.Sockets; [STAThread] static void Main(string[] args) { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Bind(new IPEndPoint(IPAddress.Any, 8002)); socket.Connect(new IPEndPoint(IPAddress.Broadcast, 8001)); socket.Send(System.Text.ASCIIEncoding.ASCII.GetBytes("hello")); int availableBytes = socket.Available; if (availableBytes > 0) { byte[] buffer = new byte[availableBytes]; socket.Receive(buffer, 0, availableBytes, SocketFlags.None); // buffer has the information on how to connect to the server } }
我想说最好的方法是使用Bonjour/Zeroconf/mDNS进行C#; 很多想法让它与网络相得益彰; 如果可能的话,它会随着时间的推移而减少频率等等.有Mono.Zeroconf,我在Apple SDK中读到了一个较旧的.NET项目,但我还没有找到它.
所以,最简单的办法是安装用于Windows的Bonjour,然后拿到了Mono.Zeroconf Windows二进制尝试的例子MZClient.exe
丢弃Mono.Zeroconf.dll
和/或Mono.Zeroconf.Providers.Bonjour.dll
到项目中引用而归.
像这样的东西:
var service = new Mono.Zeroconf.RegisterService { Name = "Use Me for Stuff", RegType = "_daap._tcp", ReplyDomain = "local.", Port = 0024200, TxtRecord = new Mono.Zeroconf.TxtRecord { {"I have no idea what's going on", "true"}} }; service.Register(); var browser = new Mono.Zeroconf.ServiceBrowser(); browser.ServiceAdded += delegate(object o, Mono.Zeroconf.ServiceBrowseEventArgs args) { Console.WriteLine("Found Service: {0}", args.Service.Name); args.Service.Resolved += delegate(object o, Mono.Zeroconf.ServiceBrowseEventArgs args) { var s = args.Service; Console.WriteLine( "Resolved Service: {0} - {1}:{2} ({3} TXT record entries)", s.FullName, s.HostEntry.AddressList[0], s.Port, s.TxtRecord.Count); }; args.Service.Resolve(); }; browser.Browse("_daap._tcp", "local");