//启动接收数据
private void button1_Click(object sender, System.EventArgs e)
{;
if (udpClient!=null)
{;
UdpThread.Abort();
Thread.Sleep(TimeSpan.FromMilliseconds(500d));
udpClient.Close();
};;
try
{;
udpClient=new UdpClient(int.Parse(textBox1.Text));
UdpThread=new Thread(new ThreadStart(UdpReciveThread));
UdpThread.Start();
};
catch(Exception y)
{;
MessageBox.Show(this,y.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
};
};
/// <summary>
/// udp连接
/// </summary>
public UdpClient udpClient;
public Thread UdpThread;
//接收数据线程
void UdpReciveThread()
{;
IPEndPoint remoteHost=null;
listBox1.Items.Add("启动");
while(udpClient!=null && Thread.CurrentThread.ThreadState.Equals(ThreadState.Running))
{;
try
{; listBox1.Items.Add("等待连接");
byte buf=udpClient.Receive(ref remoteHost);
string bufs=Encoding.UTF8.GetString(buf);
listBox1.Items.Add(string.format("主机:{;0}; 端口:{;1}; 数据报长度:{;2}; ",remoteHost.Address,remoteHost.Port,buf.Length) );
listBox1.Items.Add(bufs);
};
catch(Exception y)
{;
listBox1.Items.Add(y.Message);
listBox1.Items.Add(y.Source);
};
};
listBox1.Items.Add("结束");
};
//发数据
private void button2_Click(object sender, System.EventArgs e)
{;
try
{;
// IPHostEntry rHost=Dns.GetHostByName(textBox3.Text);
UdpClient uc=new UdpClient(textBox3.Text,int.Parse(textBox4.Text));
byte sendbuf=Encoding.UTF8.GetBytes(textBox2.Text);
uc.Send(sendbuf, sendbuf.Length);
};
catch(Exception y)
{;
MessageBox.Show(this,y.Message,"发送失败",MessageBoxButtons.OK,MessageBoxIcon.Hand);
};;
};
};
};