有一个表单有两个按钮。一个按钮(CreateGame)使用Udpclient发送广播消息然后监听加入玩家的ip并立即打开form2,当点击加入游戏(button2)听主持人时ip然后发送消息到hostIP并打开form2.I想在等待主机的ip(点击加入游戏)时打开新表单,当它收到ip,关闭表单时。有办法吗?这是代码。
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
byte[] data = ASCIIEncoding.ASCII.GetBytes("Created.");
UdpClient broadcaster = new UdpClient(1500);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Broadcast, 1500);
broadcaster.Send(data, data.Length, endPoint);
UdpClient listener = new UdpClient(1501);
IPEndPoint endxPoint = new IPEndPoint(IPAddress.Any, 1501);
Byte[] receivebytes = listener.Receive(ref endxPoint);
string clientIP = Convert.ToString(endxPoint.Address);
broadcaster.Close();
listener.Close();
Form2 a = new Form2(clientIP,"host");
a.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
UdpClient receiver = new UdpClient(1500);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 1500);
Byte[] receivebytes = receiver.Receive(ref endPoint);
string hostIP = Convert.ToString(endPoint.Address);
UdpClient receiverx = new UdpClient(1501);
IPEndPoint hostPoint = new IPEndPoint(IPAddress.Parse(hostIP), 1501);
byte[] data = ASCIIEncoding.ASCII.GetBytes("Connected.");
receiverx.Send(data, data.Length, hostPoint);
receiver.Close();
receiverx.Close();
Form2 a = new Form2(hostIP,"client");
a.Show();
}