在C#中发送UDP数据包 [英] Send UDP packet in C#

查看:297
本文介绍了在C#中发送UDP数据包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!
我有一个游戏服务器(WoW).
我希望我的玩家将我的自定义补丁下载到游戏中.
我已经完成了一个检查更新/下载内容的程序.
如果玩家拥有我的所有补丁,我希望程序将数据包发送到游戏服务器.我不需要服务器的任何响应,它将处理它,但这是另一回事.
所以我想知道如何将数据包发送到服务器.
谢谢!

Hello everybody!
I have a game server (WoW).
I want my players to download my custom patches to the game.
I''ve done a program that checks for update/downloading things.
I want my program to send a packet to my game server if player have all my patches. I dont need any response from the server, it will handle it, but its another story.
So I want to know, how to send a packet to a server.
Thank you!

推荐答案

使用UDPClient类,这是直接来自MSDN的示例;

Use the UDPClient class, here is the example straight from MSDN;

// This constructor arbitrarily assigns the local port number.
UdpClient udpClient = new UdpClient(11000);
    try{
         udpClient.Connect("www.contoso.com", 11000);

         // Sends a message to the host to which you have connected.
         Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");

         udpClient.Send(sendBytes, sendBytes.Length);

         // Sends a message to a different host using optional hostname and port parameters.
         UdpClient udpClientB = new UdpClient();
         udpClientB.Send(sendBytes, sendBytes.Length, "AlternateHostMachineName", 11000);

         //IPEndPoint object will allow us to read datagrams sent from any source.
         IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

         // Blocks until a message returns on this socket from a remote host.
         Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); 
         string returnData = Encoding.ASCII.GetString(receiveBytes);

         // Uses the IPEndPoint object to determine which of these two hosts responded.
         Console.WriteLine("This is the message you received " +
    	                              returnData.ToString());
         Console.WriteLine("This message was sent from " +
                                     RemoteIpEndPoint.Address.ToString() +
                                     " on their port number " +
                                     RemoteIpEndPoint.Port.ToString());

          udpClient.Close();
          udpClientB.Close();

          }  
       catch (Exception e ) {
                  Console.WriteLine(e.ToString());
        }


这篇关于在C#中发送UDP数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆