C#: A multi-threaded UDP server with BackgroundWorker.
The following code shows you how to build a UDP server in C# using the UUdpClient class for the networking and BackgroundWorker class for reporting data back to the application. This particular UDP server class is designed to be used with a Windows Forms or GUI. When using the UDP server you pass a BackgroundWorker class to the constructor. You should also make sure reporting is enable on that BackgroundWorker class so that they UDP server can report data and error back to your ReportProgress even.
/*
* Created by Jimmy Burnett (jimmyburnett.com)
* User: Jim
* Date: 1/1/2010
* Time: 9:19 AM
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace JimmyBurnett
{
public class udpListener
{
private System.ComponentModel.BackgroundWorker workerUDP;
private int port=5121;
public udpListener(System.ComponentModel.BackgroundWorker workerUDP,int port)
{
this.workerUDP = workerUDP;
}
/// <summary>
/// Start the listener.
/// </summary>
public void udpListenerStart()
{
try{
this.workerUDP.ReportProgress(30,"UDP Server Starting...");
byte[] data = new byte[1024];
//IPAddress addy = IPAddress.Parse("192.168.1.1");
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, this.port);
UdpClient newsock = new UdpClient(ipep);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
data = newsock.Receive(ref sender);
//send a status back to our background worker class.
this.workerUDP.ReportProgress(30,"UDP Server Listening...");
while(true)
{
this.workerUDP.ReportProgress(30,"Received Data..");
this.workerUDP.ReportProgress(50,data.Length);
data = newsock.Receive(ref sender);
}
}catch(Exception ee){
this.workerUDP.ReportProgress(666,ee.Message);
Console.WriteLine(ee.Message) ;
}
}
}
}
