作为这个问题的后续问题,我已经在我的本地机器上运行了一个解决方案,但是没有在网络上的机器上运行.
我不太了解那些基础知识以外的插座,所以请耐心等待.目标是让客户端在本地网络上查找服务器,这是一些剪切/粘贴/编辑代码的结果.
这是客户端代码:
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10294); byte[] data = new byte[1024]; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 10); string welcome = "What's your IP?"; data = Encoding.ASCII.GetBytes(welcome); client.SendTo(data, data.Length, SocketFlags.None, ipep); IPEndPoint server = new IPEndPoint(IPAddress.Any, 0); EndPoint tmpRemote = (EndPoint)server; data = new byte[1024]; int recv = client.ReceiveFrom(data, ref tmpRemote); this.IP.Text = ((IPEndPoint)tmpRemote).Address.ToString(); //set textbox this.Port.Text = Encoding.ASCII.GetString(data, 0, recv); //set textbox client.Close(); }
这是服务器代码:
int recv; byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 10294); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); newsock.Bind(ipep); newsock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Any,IPAddress.Parse("127.0.0.1"))); while (true) { Console.WriteLine("Waiting for a client..."); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint tmpRemote = (EndPoint)(sender); data = new byte[1024]; recv = newsock.ReceiveFrom(data, ref tmpRemote); Console.WriteLine("Message received from {0}:", tmpRemote.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); string welcome = "7010"; data = Encoding.ASCII.GetBytes(welcome); newsock.SendTo(data, data.Length, SocketFlags.None, tmpRemote); }
它可以在我的本地机器(服务器和客户端)上查找,但当我在同一网络上尝试另一台机器时,我得到"现有连接被远程主机强行关闭"
我意识到我需要添加很多try/catch,但我只是想先了解一下这是如何工作的.