所以,这就是事情,我为游戏创建服务器/客户端环境,其中端口转发计算机充当服务器,客户端发送第一条UDP消息进行连接并获取接受消息然后在成功连接后开始发送游戏内UDP消息。 问题是,当我使用本地IP说服务器使用10.0.0.7而客户端使用10.0.0.4时,一切正常:
但是当我使用外部IP时:
最后想知道这个问题是从代码中得到的,还是从我认为的真正来自路由器,NAT,防火墙或类似的东西。 (注意:客户端发送到服务器的8888端口,服务器通过客户端的本地端口发回,应该是这样。)
以下是为Unity编写的客户端代码:
void Start()
{
client = new UdpClient();
client.Connect(IPAddress.Parse("<Global IP>"), 8888);
client.BeginReceive(new AsyncCallback(ReadMessage), client);
}
private void ReadMessage(IAsyncResult result)
{
IPEndPoint ipEndPoint = null;
string message = Encoding.ASCII.GetString(client.EndReceive(result, ref ipEndPoint));
print("Got: " + message);
string[] wholeMessages = message.Split('#');
for (int w = 0; w < wholeMessages.Length - 1; w++)
{
string[] parts = wholeMessages[w].Split('$');
if (!connected && parts.Length == 3 && parts[0] == "accept" && int.TryParse(parts[1], out ID))
{
connected = true;
code = parts[2];
}
}
client.BeginReceive(new AsyncCallback(ReadMessage), client);
}
public void SendUDP(string message)
{
client.Send(Encoding.ASCII.GetBytes(message), message.Length);
}
答案 0 :(得分:0)
好的,经过多次试验和错误后,这对我有用......
//服务器代码
private static UdpClient udpClient;
static void Main(string[] args)
{
Console.WriteLine("Server initiated...");
udpClient = new UdpClient(8888);
}
private static void ReadMessage()
{
while (true)
{
try
{
IPEndPoint IPEP = null;
string message = Encoding.ASCII.GetString(udpClient.Receive(ref IPEP));
}
}
}
private static void SendUDP(IPEndPoint e,string message)
{
new UdpClient().Send(Encoding.ASCII.GetBytes(message), message.Length, e);
}
//客户端代码
private IPAddress ip;
void Start()
{
ip = Dns.GetHostAddresses("HOSTNAME")[0];
client = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
udpThread = new Thread(new ThreadStart(ReadMessage))
{
IsBackground = true
};
udpThread.Start();
}
private void ReadMessage()
{
while (true)
{
try
{
IPEndPoint IPEP = null;
byte[] data = client.Receive(ref IPEP);
string message = Encoding.ASCII.GetString(data);
}
}
}
public void SendUDP(string message)
{
client.Send(Encoding.ASCII.GetBytes(message), message.Length, new IPEndPoint(ip, 8888));
}