我使用c#MVC 4作为服务器,这意味着我没有视图,它当前接受对控制器的Http / s请求,处理它们,查询数据库并将json对象返回给用户。 / p>
我想增强我的服务器并添加一个udp(或tcp,我尚未完全决定)监听器。
问题是我没有看到有人这样做,每个人都使用控制台应用程序或类似WCF,因为侦听器可以通过某种动作触发。
我有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);
}
我的问题是,如何在运行服务器时将侦听器设置为开始工作?
框架:.Net framework 4.5
输出类型:类库