我正在使用多播网络为Windows Phone 8实现多人纸牌游戏。 但是,当我尝试链接Windows手机和模拟器时没有任何反应(也没有错误)。
我可以使用Internet Explorer浏览网页,以便我的模拟器连接到互联网。
我是否必须在模拟器上进行特殊操作才能使其进行多播操作? 或者代码中是否缺少某些内容?
以下是代码:
初始化
channel = new UdpChannel(IPAddress.Parse("224.109.108.106"), 3000);
this.channel.OnAfterOpened += new EventHandler<UdpPacketEventArgs>(channel_OnAfterOpen);
this.channel.OnPacketReceived += new EventHandler<UdpPacketEventArgs(Channel_PacketReceived);
this.channel.Open();
我的多播操作类:
public UdpChannel(IPAddress address, int port)
{
groupAddress = address;
localPort = port;
client = new UdpAnySourceMulticastClient(groupAddress, localPort);
}
public void Open()
{
if (!isJoined)
{
this.client.BeginJoinGroup(
result =>
{
try
{
this.client.EndJoinGroup(result);
isJoined = true;
this.AfterOpened();
this.Receive();
}
catch (Exception e)
{
throw e;
}
}, null);
}
}
private void AfterOpened()
{
EventHandler<UdpPacketEventArgs> handler = this.OnAfterOpened;
if (handler != null)
handler(this, new UdpPacketEventArgs(string.Empty, string.Empty));
}
private void Receive()
{
if (isJoined)
{
Array.Clear(this.buffer, 0, this.buffer.Length);
this.client.BeginReceiveFromGroup(this.buffer, 0, this.buffer.Length, result =>
{
if (!isDisposed)
{
IPEndPoint source;
try
{
this.client.EndReceiveFromGroup(result, out source);
this.AfterReceived(source, this.buffer);
this.Receive();
}
catch
{
isJoined = false;
this.Open();
}
}
}, null);
}
}
public void SendTo(int cardId)
{
byte[] data = Encoding.UTF8.GetBytes(cardId.ToString());
if (isJoined)
{
this.client.BeginSendToGroup(data, 0, data.Length,
result =>
{
this.client.EndSendToGroup(result);
}, null);
}
}
private void AfterReceived(IPEndPoint source, byte[] p)
{
EventHandler<UdpPacketEventArgs> handler = this.OnPacketReceived;
if (handler != null)
handler(this, new UdpPacketEventArgs(source.Address.ToString(), Encoding.UTF8.GetString(p, 0, p.Length)));
}
private void BeforeClose()
{
EventHandler<UdpPacketEventArgs> handler = this.OnBeforeClosing;
if (handler != null)
handler(this, new UdpPacketEventArgs(string.Empty, string.Empty));
}
#region IDisposable
public void Dispose()
{
if (!isDisposed)
{
Dispose(true);
GC.SuppressFinalize(this);
}
isDisposed = true;
}
~UdpChannel()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
if (disposing)
{
client.Dispose();
}
}
我的活动
public class UdpPacketEventArgs : EventArgs
{
public string Message { get; private set; }
public string Source { get; private set; }
public UdpPacketEventArgs(string source, string data)
{
this.Message = data;
this.Source = source;
}
}
我的事件处理程序
private void Channel_PacketReceived(object sender, UdpPacketEventArgs e)
{
MessageBox.Show("Something Received");
}
private void channel_OnAfterOpen(object sender, UdpPacketEventArgs e)
{
this.Status.Text = "Connected";
}