我在Windows Phone 8上制作GPS应用程序并需要将一些数据发送到服务器以搜索数据库中的某些内容并获得回复。所以我让客户端像in this article一样正确。 但我只是想发送一些内容,所以我将应用页面上的代码更改为:
var result = client.Send("my.outer.ip.address", 35454, AddressTextBox.Text); // The port choosed randomly, the sever has the same
AddressTextBox.Text = result;
result = client.Receive(35454);
AddressTextBox.Text = result;
然后我写了一些测试UDP服务器,它是:
class Program
{
static void Main(string[] args)
{
int receive;
var data = new byte[1024];
var endpoint = new IPEndPoint(IPAddress.Any, 35454);
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(endpoint);
Console.WriteLine("Waiting for a client...");
var sender = new IPEndPoint(IPAddress.Any, 35454);
var tmpRemote = (EndPoint)sender;
receive = socket.ReceiveFrom(data, ref tmpRemote);
Console.WriteLine("Message received from {0}: ", tmpRemote.ToString());
Console.WriteLine(Encoding.Unicode.GetString(data, 0, receive));
var answer = "This is the answer";
data = Encoding.Unicode.GetBytes(answer);
if(socket.Connected)
socket.Send(data);
while (true)
{
if(!socket.Connected)
{
Console.WriteLine("Client Disconnected");
break;
}
data = new byte[1024];
receive = socket.ReceiveFrom(data, ref tmpRemote);
if (receive == 0)
break;
Console.WriteLine(Encoding.Unicode.GetString(data, 0, receive));
socket.Close();
}
}
}
但它不起作用,没有错误,只是不起作用。所有防火墙都被禁用。通过家庭Wi-Fi连接。有人可以帮帮我吗?
UPD: 我试图让测试客户端不是Windows窗体。当我将消息发送到127.0.0.1和本地IP时,它可以工作。但是,当我向外部IP发送消息(我通过互联网上的特殊网站,我认为你知道其中很多)时,服务器什么也得不到。这是测试客户端代码:
byte[] packetData = Encoding.ASCII.GetBytes("<Packet of Some Data>");
var ip = "127.0.0.1";
var port = 35454;
var ep = new IPEndPoint(IPAddress.Parse(ip), port);
var client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.SendTo(packetData, ep);
但是在Windows Phone 8上,它肯定无法正常工作,因为它在自己的适配器中使用,并且工作就像是真正的其他设备。所以我需要它在互联网上工作。