Udp connection test : UdpClient « Network « C# / CSharp Tutorial






using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

class MainClass
{
    private static void Main() 
    {
        string IP = "127.0.0.1";
        int port = 9999;

        IPEndPoint remoteEndPoint =  new IPEndPoint(IPAddress.Parse(IP), port);

        Thread receiveThread = new Thread(ReceiveData);
        receiveThread.IsBackground = true;
        receiveThread.Start();

        UdpClient client = new UdpClient();

        try
        {
            string text;
            do
            {
                text = Console.ReadLine();

                if (text.Length != 0)
                {
                    byte[] data = Encoding.UTF8.GetBytes(text);
                    client.Send(data, data.Length, remoteEndPoint);
                }
            } while (text.Length != 0);
        }
        catch (Exception err)
        {
            Console.WriteLine(err.ToString());
        }
        finally
        {
            client.Close();
        }
    }

    private static void ReceiveData() 
    {
        UdpClient client = new UdpClient(999);
        while (true) 
        {
            try 
            {
                IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
                byte[] data = client.Receive(ref anyIP);
                string text = Encoding.UTF8.GetString(data);
                Console.WriteLine(">> " + text);
            } 
            catch (Exception err) 
            {
                Console.WriteLine(err.ToString());
            }
        }
    }
}








33.13.UdpClient
33.13.1.Use UdpClient
33.13.2.Binary UdpClient: send binary data to Udp server
33.13.3.Binary Udp Server: receive binary data from Udp client
33.13.4.UdpClient: Send
33.13.5.UdpClient: receive for multicast group
33.13.6.Udp connection test