I'm using c# MVC 4 as server, meaning I have no Views in it and it currently accept Http/s requests to the controllers, process them, query the db and returns a json object to the user.
I would like to enhance my server and add a udp (or tcp, i haven't completely decided yet) listener.
Problem is I haven't seen someone does it, everyone use either Console Application or WCF-like because the listener can be triggered by some sort of action.
I have a standard code from CodeProject
// Create UDP client
UdpClient client = new UdpClient(localPort);
UdpState state = new UdpState(client, remoteSender);
// Start async receiving
client.BeginReceive(new AsyncCallback(DataReceived), state);
private static void DataReceived(IAsyncResult ar)
{
UdpClient c = (UdpClient)((UdpState)ar.AsyncState).c;
IPEndPoint wantedIpEndPoint = (IPEndPoint)((UdpState)(ar.AsyncState)).e;
IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receiveBytes = c.EndReceive(ar, ref receivedIpEndPoint);
// Check sender
bool isRightHost = (wantedIpEndPoint.Address.Equals(receivedIpEndPoint.Address)
|| wantedIpEndPoint.Address.Equals(IPAddress.Any);
bool isRightPort = (wantedIpEndPoint.Port == receivedIpEndPoint.Port)
|| wantedIpEndPoint.Port == 0;
if (isRightHost && isRightPort)
{
// Convert data to ASCII and print in console
string receivedText = ASCIIEncoding.ASCII.GetString(receiveBytes);
Console.Write(receivedText);
}
// Restart listening for udp data packages
c.BeginReceive(new AsyncCallback(DataReceived), ar.AsyncState);
}
My issue is, How can I set the listener to start working when I run the server?
Framework : .Net framework 4.5
Output type : Class Library