Iam嘗試從我的客戶端向我的服務器發送消息(通過UDP)。服務器應該回答這個消息,如果客戶端收到這個答案,他應該打印出一條消息。C#UDP服務器/客戶端 - NAT
如果我運行我的本地網絡上的客戶端和服務器一切正常。 如果我嘗試通過互聯網從另一臺PC連接到我的網絡外,服務器收到客戶端請求,發回答案,但客戶端永遠不會收到此答案。客戶端和服務器都在NAT後面,但我在服務器的NAT上轉發了這些端口,並且服務器擁有了自己的DNS。我已經嘗試過NAT遍歷,但在接收到客戶端請求後,它給了我與服務器的IPEndPoint相同的IP和端口地址。
我不知道如何解決這個問題,所以任何指導都將不勝感激。
客戶
public static void Main()
{
Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
receiveThread.Start();
object[] oData = {1};
sendData(oData, 0,0, "Li");
while (true)
{
Console.ReadLine();
}
}
private void receiveData()
{
string receivePort = 8080;
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.ReceiveTimeout = 1000;
IPEndPoint end = new IPEndPoint(IPAddress.Any, receivePort);
client.Bind(end);
while (true)
{
try
{
byte[] data = new byte[1024];
client.Receive(data, 0, data.Length, SocketFlags.None);
object[] receivedObj = Deserialize(data);
string sType = (string)receivedObj[3];
if (sType == "Li")
{
console.WriteLine("received Li");
}
}
catch (Exception err)
{
Console.WriteLine(err.ToString());
}
}
}
public static void sendData(object[] oData, int iFrom, int iTo, string sType)
{
string sendPort = 17171;
UdpClient client = new UdpClient();
string IP = "ThisIsTheDNSofmyServer.com"; //ServerDNS
//string IP = "192.168.xxx.xxx"; //serverIP in LAN
if (IP.StartsWith("T"))
{
IP = (Dns.GetHostAddresses(IP))[0].ToString();
}
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), sendPort);
oData[1] = iFrom;
oData[2] = iTo;
oData[3] = sType;
Byte[] data = Serialize(oData);
client.Send(data, data.Length, remoteEndPoint);
}
的server's代碼幾乎是相同的:
public static void Main()
{
Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
receiveThread.Start();
while (true)
{
Console.ReadLine();
}
}
private static void ReceiveData()
{
int receivePort = 17171;
UdpClient client = new UdpClient(receivePort);
while (true)
{
try
{
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
data = client.Receive(ref anyIP);
object[] receivedObj = Deserialize(data);
//if I receive data send an Answer
sendData(receivedObj, 0,0,"Li",anyIP.Address.ToString());
}
catch (Exception err)
{
Console.WriteLine(err.ToString());
}
}
}
private static void sendData(object[] oData, int iFrom, int iTo, string sType, string IP)
{
int sendPort = 8080;
object[] paket = { oData, iFrom, iTo, sType };
UdpClient client = new UdpClient();
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), sendPort);
client.Send(data, data.Length, remoteEndPoint);
}
不確定,但您可以檢查防火牆設置 – 2012-02-22 11:46:36
關閉客戶端和服務器上的所有防火牆以消除潛在問題。如果您的客戶端向服務器發送消息,並且服務器接收到該消息,則客戶端肯定會收到服務器的答覆。除了第三方防火牆之外,您還可以使用Windows防火牆。嘗試打開客戶端和服務器路由器的DMZ /端口轉發。如果它仍然不起作用,我不太確定它可能是什麼。 – Jason 2012-02-24 03:41:12