//Main
{
//create a new server
Console.WriteLine("Iniciando");
var server = new UdpListener();
Console.WriteLine("Iniciado");
//start listening for messages and copy the messages back to the client
Task.Factory.StartNew(async () =>
{
int count = 1;
while (true)
{
var received = await server.Receive();
//server.Reply("copy " + received.Message, received.Sender);
if (received.Message == "quit")
break;
Console.WriteLine("recibido.." + received.Message + " " + count);
count++;
}
});
}
public struct Received
{
public IPEndPoint Sender;
public string Message;
}
//Server
class UdpListener : UdpBase
{
private IPEndPoint _listenOn;
public UdpListener()
: this(new IPEndPoint(IPAddress.Any, 32123))
{
}
public UdpListener(IPEndPoint endpoint)
{
_listenOn = endpoint;
Client = new UdpClient(_listenOn);
}
public void Reply(string message, IPEndPoint endpoint)
{
var datagram = Encoding.ASCII.GetBytes(message);
Client.Send(datagram, datagram.Length, endpoint);
}
}
abstract class UdpBase
{
protected UdpClient Client;
protected UdpBase()
{
Client = new UdpClient();
}
public async Task<Received> Receive()
{
var result = await Client.ReceiveAsync();
return new Received()
{
Message = Encoding.ASCII.GetString(result.Buffer, 0, result.Buffer.Length),
Sender = result.RemoteEndPoint
};
}
}
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.