Reputation: 21
I am trying to simulate a Client - Server scenario on my machine in c#. But when i am executing it an exception pops up saying:
No such host is known
My code:
namespace TCPClient
{
public class Program
{
public static void Main(string[] args)
{
UdpClient udpc = new UdpClient(args[0], 2055);
IPEndPoint ep = null;
while (true)
{
Console.Write("Name: ");
string name = Console.ReadLine();
if (name == "") break;
byte[] sdata = Encoding.ASCII.GetBytes(name);
udpc.Send(sdata, sdata.Length);
byte[] rdata = udpc.Receive(ref ep);
string job = Encoding.ASCII.GetString(rdata);
Console.WriteLine(job);
}
}
}
}
I don't understand where I'm going wrong.
Upvotes: 0
Views: 2247
Reputation: 21
thanks Dev's ! your answers were helpful, however I found an easiest way for the same.
public class Program
{
public static void Main(string[] args)
{
UdpClient udpc = new UdpClient( System.Net.Dns.GetHostName(), 2055);
IPEndPoint ep = null;
while (true)
{
Console.Write("Name: ");
string name = Console.ReadLine();
if (name == "") break;
byte[] sdata = Encoding.ASCII.GetBytes(name);
udpc.Send(sdata, sdata.Length);
byte[] rdata = udpc.Receive(ref ep);
string job = Encoding.ASCII.GetString(rdata);
Console.WriteLine(job);
}
}
}
Upvotes: 1
Reputation: 3970
I do believe your issue lies within this call:
byte[] rdata = udpc.Receive(ref ep)
The problem is that, in order to be able to listen to any incoming content, you need first to bind the UdpClient to a valid endpoint - like this:
IPEndPoint ep = new IPEndPoint(IPAddress.Any, 8192);
//You will be listening to port 8192.
Also, keep in mind that you can't both listen AND emit from the same UdpClient; You'll need two clients, and if you want to use the same IP Port for both, you'll need to initialize the class using the SocketOptionName.ReuseAddress
parameter. A good example is provided on the following post:
Connecting two UDP clients to one port (Send and Receive)
Upvotes: 0
Reputation: 151588
Isolate the issue. You're calling new UdpClient(args[0], 2055)
and udpc.Receive(ref ep)
that can throw this exception, but don't say which one does. Either debug it or try it with a constant string:
string host = args[0];
new UdpClient(host, 2055);
You'll then see that host
is most probably not an existing hostname. If it is, check what you are doing with ep
: nothing, so it will be null
. I guess you'll want to listen to any UDP datagram as explained in the documentation, so specify the endpoint:
ep = new IPEndPoint(IPAddress.Any, 0);
Upvotes: 0