Sending and Receiving UDP packets

后端 未结 2 1361
情歌与酒
情歌与酒 2020-12-06 08:11

The following code sends a packet on port 15000:

int port = 15000;
UdpClient udp = new UdpClient();
//udp.EnableBroadcast = true;  //This was suggested in a          


        
相关标签:
2条回答
  • 2020-12-06 08:33

    Here is the simple version of Server and Client to send/receive UDP packets

    Server

    IPEndPoint ServerEndPoint= new IPEndPoint(IPAddress.Any,9050);
    Socket WinSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    WinSocket.Bind(ServerEndPoint);
    
    Console.Write("Waiting for client");
    IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0)
    EndPoint Remote = (EndPoint)(sender);
    int recv = WinSocket.ReceiveFrom(data, ref Remote);
    Console.WriteLine("Message received from {0}:", Remote.ToString());
    Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
    

    Client

    IPEndPoint RemoteEndPoint= new IPEndPoint(
    IPAddress.Parse("ServerHostName"), 9050);
    Socket server = new Socket(AddressFamily.InterNetwork,
                               SocketType.Dgram, ProtocolType.Udp);
    string welcome = "Hello, are you there?";
    data = Encoding.ASCII.GetBytes(welcome);
    server.SendTo(data, data.Length, SocketFlags.None, RemoteEndPoint);
    
    0 讨论(0)
  • 2020-12-06 08:35

    There is actually a very good UDP example of a server and listener on MSDN: Simple UDP example

    0 讨论(0)
提交回复
热议问题