我想在Windows Phone 7.1上准备app以在相机和手机(Wanscam相机)之间发送/接收UDP数据报。我已经阅读了很多关于此的讨论,现在我不知道它可以在OS 7.1上实现。
一开始我必须找到相机IP。我根据Device Discovery in Windows phone 7编写了一些代码:
var ipAddress = IPAddress.Parse(IP_BROADCAST);
var endpoint = new IPEndPoint(ipAddress, portToScan);
byte[] data = packet.GetRawPacketBytes();
var args = new SocketAsyncEventArgs();
args.RemoteEndPoint = endpoint;
args.SetBuffer(data, 0, data.Length);
args.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
recevingEnabled = true;
Timer timer = new Timer(TimerCallback, null, 0, 1000);
while (recevingEnabled)
{
Receive(portToScan);
}
});
bool result = socket.SendToAsync(args);
接收方法:
public void Receive(int portNumber)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = new IPEndPoint(IPAddress.Any, portNumber);
socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
...
clientDone.Set();
});
clientDone.Reset();
socket.ReceiveAsync(socketEventArg);
clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
1)当我调用此方法时,我从相机接收数据但我无法在socketEventArg中找到发件人IP地址。
2)我不知道在本地网络连接更多摄像机时可以接收更多数据报。
下一点对我来说更奇怪。我想收听端口并接收相机将发送到手机的数据报(仅来自相机IP的数据报)。根据消息来源,我不知道这是可能的:Sockets for Windows Phone。
我的方法看起来像while(true)TryReceiving;但它不起作用。我决定检查笔记本电脑上的简单python脚本和我的简单WP7应用程序之间的udp通信。当我查看结果时,我感到很惊讶。
我将手机(192.168.1.102)插入笔记本电脑(192.168.1.104)并开始调试。接下来我发送了一些数据报到笔记本电脑我的笔记本电脑收到了python脚本中的数据报并转发了消息。不幸的是,我的手机应用程序无法接收任何数据报。我试着解决这个问题,但我无法理解问题出在哪里。我通过Wireshark嗅探我的网络,我看到我的笔记本电脑转发消息到手机。我尝试在每个组合中将 ReceiveAsync 更改为 ReceiveFromAsync ,将 SendToAsync 更改为 SendAsync 。
代码:
private void ReceiveTask()
{
byte[] data = currentStunServer.HelloToAddressPacket().GetRawPacketBytes();
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.104"), 32110);
socketEventArg.SetBuffer(data, 0, data.Length);
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
while (true)
{
SocketAsyncEventArgs socketEventArg2 = new SocketAsyncEventArgs();
socketEventArg2.RemoteEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.104"), 32110);
socketEventArg2.SetBuffer(new Byte[2048], 0, 2048);
socketEventArg2.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s2, SocketAsyncEventArgs e2)
{
if (e2.BytesTransferred > 0)
{
string response;
response = Encoding.UTF8.GetString(e2.Buffer, e.Offset, e2.BytesTransferred);
response = response.Trim('\0');
}
clientDone.Set();
});
clientDone.Reset();
UdpSocket2.ReceiveAsync(socketEventArg2);
clientDone.WaitOne(1000);
}
});
bool result = UdpSocket2.SendToAsync(socketEventArg);
while (true)
{
Receive();
System.Threading.Thread.Sleep(1000);
}
}
有没有解决问题的方法?也许Windows Phone 8提供了一些解决方案? 抱歉我的英文。