当前位置: 代码迷 >> C# >> 跪求大神解决,UDP内网和外网通信有关问题
  详细解决方案

跪求大神解决,UDP内网和外网通信有关问题

热度:87   发布时间:2016-05-05 03:56:06.0
跪求大神解决,UDP内网和外网通信问题
我在博客上看到外网到内网UDP通信的解决方法:内网主动和外网连接,外网获取其代理服务器的IP地址和临时分配的通讯端口,向其发送UDP消息即可。(http://blog.csdn.net/foas/article/details/338983)
于是我编写了以下代码:

//Server端的UDPLIstener
public string[] Listener()
{
string returnData = string.Empty;
string[] msgArray;
try
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 5000);
UdpClient udpClient = new UdpClient(RemoteIpEndPoint);
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
returnData += Encoding.ASCII.GetString(receiveBytes);
returnData += ";;" + RemoteIpEndPoint.Address.ToString() + ";;" + RemoteIpEndPoint.Port.ToString();
msgArray = Regex.Split(returnData, ";;");
//msg;;ip;;port
udpClient.Close();
}
catch (Exception ex)
{
//do something here
throw;
}
return msgArray;
}


//接收到客户端的消息后,向客户端发送消息,其中ip和port为上一个方法保存的ip和port
public static void Sender(IPAddress ip, int port, string msg)
{
try
{
IPEndPoint ipep = new IPEndPoint(ip, 5000);
UdpClient udpClient = new UdpClient();
Byte[] sendBytes = Encoding.ASCII.GetBytes(msg);
//udpClient.JoinMulticastGroup(ip);
udpClient.Send(sendBytes, sendBytes.Length, ipep);//发送
udpClient.Close();//断开连接
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}


//问题是在客户端的UDPListener要侦听哪个端口,这样写客户端仍然收不到消息
public string Listener()
{
string returnData = string.Empty;
try
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 5000);
UdpClient udpClient = new UdpClient(RemoteIpEndPoint);
//UdpClient udpClient = new UdpClient(5000, AddressFamily.InterNetwork);
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
returnData += Encoding.ASCII.GetString(receiveBytes);
udpClient.Close();
}
catch (Exception ex)
{
//do something here
MessageBox.Show(ex.ToString());
throw;
}
return returnData;//如果未接收到消息,返回值为空
}


跪求大神解决
------解决思路----------------------
你的方法无效,UDP是无连接协议,发送方的端口是由发送方随机生成的(根据不同的网络环境,发送方的IP也有可能是在地址池中随机选取的),发送完以后,该IP+端口就已经无效了。
有两种方法,在内网边界上,做端口映射,指定固定的IP+UDP端口给内网的客户端,好处是可以自由双向通信,不需要先由内网端发起通信,这种方案需要你有网络的管理权限
或者,使用TCP协议,由内网发起到外网端的连接,外网端接收以后会建立一条连接,在主动关闭前会一直存在,这样外网端可以根据对端的IP+端口给内网发信息。
------解决思路----------------------
UDP打洞,打洞的前提是你有一个公网的IP做为中转。
------解决思路----------------------
一楼说的就是我要说的,谢谢
  相关解决方案