点击按钮,触发线程,在线程中调用主UI线程。
private void AddMessage(string message)
{
// InvokeRequired需要比较调用线程ID和创建线程ID
// 如果它们不相同则返回true
if (this.lbClient.InvokeRequired)
{
worker = new Worker(AddMessage);
this.Invoke(worker, new object[] { message });
}
else
{
this.lbClient.Items.Add(message);
}
}
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(HandleMsg));
thread.Start();
}
public void HandleMsg()
{
IPEndPoint localEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9060);
ArrayList list = new ArrayList(10);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
server.Bind(localEP);
EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
int recv;
byte[] data;
while (true)
{
data = new byte[1024];
recv = 0;
recv = server.ReceiveFrom(data, ref remoteEP);
AddMessage("Waiting for a client");
String message = Encoding.ASCII.GetString(data, 0, recv);
switch (message)
{
case "join":
worker.Invoke(string.Format("Received from {0}: ", remoteEP.ToString()));
list.Add(remoteEP);
break;
case "quit":
list.Remove(remoteEP);
break;
default:
int i = 0;
String Data = Encoding.ASCII.GetString(data) + remoteEP.ToString();
while (i < list.Count)
{
server.SendTo(Encoding.ASCII.GetBytes(remoteEP.ToString()), recv, SocketFlags.None, (EndPoint)list[i]);
++i;
}
break;
}
}
}