从使用 UdpClient 接收的 UDP 包中获取客户端 IP
我正在 系统的帮助下开发一款动作多人游戏.Net.Sockets.UdpClient 类。
它适合两个玩家,因此一个人应该打开服务器并等待传入连接。另一个玩家输入主机 IP 并尝试发送“ping”,以确保可以建立连接并且有一个开放的服务器。然后主人用“乒”的一声回应。
一旦游戏运行,双方都必须互相发送udp消息,因此他们都需要对手的ip地址。
当然服务器也可以输入客户端IP,但这对我来说似乎没有必要。
当收到“ping”消息时,如何从 udp 包中获取客户端 IP?
这是我的接收代码(服务器等待 ping):
private void ListenForPing()
{
while (!closeEverything)
{
var deserializer = new ASCIIEncoding();
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] recData = udp.Receive(ref anyIP);
string ping = deserializer.GetString(recData);
if (ping == "ping")
{
Console.WriteLine("Ping received.");
InvokePingReceiveEvent();
}
}
}
I am developing an action multiplayer game with the help of the System.Net.Sockets.UdpClient class.
It's for two players, so one should open a server and wait for incoming connections. The other player inputs the host IP and tries to send a "ping", to make sure a connection is possible and there is an open server. The host then responds with a "pong".
Once the game is running, both have to send udp messages to each other, so they both need the opponents ip address.
Of course the server could also input the clients IP, but that seems unneccessary to me.
How can I get the clients IP from the udp package when the "ping" message is received?
Here is my receiving code (server waiting for ping):
private void ListenForPing()
{
while (!closeEverything)
{
var deserializer = new ASCIIEncoding();
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] recData = udp.Receive(ref anyIP);
string ping = deserializer.GetString(recData);
if (ping == "ping")
{
Console.WriteLine("Ping received.");
InvokePingReceiveEvent();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的示例中,当客户端连接时,anyIP IPEndPoint 对象将包含客户端连接的地址和端口。
In your example, when a client connects, the anyIP IPEndPoint object will contain the address and port of the client connection.
http://msdn.microsoft.com/en -us/library/system.net.sockets.udpclient.receive.aspx
http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.receive.aspx