測試用代碼,已編譯運行通過,保留,省的以后碰到這類需求,可直接用。
先上圖,一張圖頂100句話。
public partial class Form1 : Form
{
UdpClient udpClient;
Thread UdpThread;
delegate void updateUI(string msg);
updateUI AddMsg2LogDelegate;
public Form1()
{
InitializeComponent();
AddMsg2LogDelegate = new updateUI(AddMsg2Log);
}
private void btnstartservice_Click(object sender, EventArgs e)
{
StartServer();
}
private void StartServer()
{
if (udpClient != null)
{
UdpThread.Abort();
Thread.Sleep(TimeSpan.FromMilliseconds(500d));
udpClient.Close();
}
try
{
udpClient = new UdpClient(int.Parse(textBoxPort.Text));
UdpThread = new Thread(new ThreadStart(UdpReciveThread));
UdpThread.Start();
//buttonStartServer.Enabled = false;
}
catch (Exception y)
{
MessageBox.Show(this, y.Message, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
void UdpReciveThread()
{
IPEndPoint remoteHost = null;
this.Invoke(AddMsg2LogDelegate, "啟動...");
//listBox1.Items.Add("啟動...");
while (udpClient != null && Thread.CurrentThread.ThreadState == ThreadState.Running)
{
try
{
this.Invoke(AddMsg2LogDelegate, "等待連接...");
byte[] buf = udpClient.Receive(ref remoteHost);
string bufs = Encoding.UTF8.GetString(buf);
string s = string.Format("主機:{0}; 端口:{1}; 數據報長度:{2}; ",remoteHost.Address, remoteHost.Port, buf.Length);
this.BeginInvoke(AddMsg2LogDelegate, s);
this.BeginInvoke(AddMsg2LogDelegate, bufs);
}
catch (Exception y)
{
this.Invoke(AddMsg2LogDelegate, y.Message);
}
}
this.Invoke(AddMsg2LogDelegate, "結束...");
}
public void AddMsg2Log(string message)
{
listBoxLog.Items.Add(message);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
System.Environment.Exit(0);
}
private void btnSendMessage_Click(object sender, EventArgs e)
{
try
{
UdpClient uc = new UdpClient(textBoxHost.Text,int.Parse(textBoxPort.Text));
byte[] sendbuf = Encoding.UTF8.GetBytes(textBoxMessage.Text);
uc.Send(sendbuf, sendbuf.Length);
}
catch (Exception y)
{
MessageBox.Show(this, y.Message, "發送失敗", MessageBoxButtons.OK,MessageBoxIcon.Hand);
}
}
private void button1_Click(object sender, EventArgs e)
{
this.listBoxLog.Items.Clear();
}
}