[英]Client - Server on same machine using UDP
我正在嘗試在C#的計算機上模擬客戶端-服務器方案。 但是當我執行它時,彈出一個異常說:
尚無此類主機
我的代碼:
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);
}
}
}
}
我不明白我要去哪里錯了。
感謝Dev的! 您的回答很有幫助,但是我找到了最簡單的方法。
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);
}
}
}
隔離問題。 您正在調用new UdpClient(args[0], 2055)
和udpc.Receive(ref ep)
,它們可能會引發此異常,但不要說是哪個異常。 調試它或嘗試使用常量字符串:
string host = args[0];
new UdpClient(host, 2055);
然后,您會看到該host
很可能不是現有主機名。 如果是這樣,請檢查您在用ep
做什么:什么都沒有,所以它將為null
。 我想您會想要聽文檔中說明的所有UDP數據報,因此請指定端點:
ep = new IPEndPoint(IPAddress.Any, 0);
我相信您的問題在於此電話中:
byte[] rdata = udpc.Receive(ref ep)
問題在於,為了能夠收聽任何傳入的內容,您需要首先將UdpClient綁定到有效的端點-如下所示:
IPEndPoint ep = new IPEndPoint(IPAddress.Any, 8192);
//You will be listening to port 8192.
另外,請記住,您不能同時收聽和發送來自同一UdpClient的消息。 您將需要兩個客戶端,並且如果要為兩個客戶端使用相同的IP端口,則需要使用SocketOptionName.ReuseAddress
參數初始化該類。 以下帖子提供了一個很好的示例:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.