作为对这个问题的一种跟进,我已经在我的本地机器上得到了一个解决方案,但在网络上的机器上却没有。
除了基础知识之外,我对套接字知之甚少,所以请耐心等待。目标是让客户端在本地网络上寻找服务器,这是一些剪切/粘贴/编辑代码的结果。
这是客户端代码:
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);
}
它可以在我的本地机器(服务器和客户端)上找到,但是当我在同一网络上尝试另一台机器时,我得到“现有连接被远程主机强行关闭”
我意识到我需要添加很多尝试/捕获,但我只是想先了解它是如何工作的。