c#-UDP-多线程收发消息的类

测试用代码,已编译运行通过,保留,省的以后碰到这类需求,可直接用。

先上图,一张图顶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();
}
}

posted @ 2017-06-14 10:08  软件开发总结  阅读(5506)  评论(4编辑  收藏  举报