Communicate Using UDP - CSharp Network

CSharp examples for Network:UDP

Description

Communicate Using UDP

Demo Code

using System;/*from  w  w  w.  j  a va2  s.c  o m*/
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
class MainClass
{
   private static int localPort;
   private static void Main()
   {
      Console.Write("Connect to IP: ");
      string IP = Console.ReadLine();
      Console.Write("Connect to port: ");
      int port = Int32.Parse(Console.ReadLine());
      IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
      Console.Write("Local port for listening: ");
      localPort = Int32.Parse(Console.ReadLine());
      Thread receiveThread = new Thread(ReceiveData);
      receiveThread.IsBackground = true;
      receiveThread.Start();
      UdpClient client = new UdpClient();
      Console.WriteLine("Type message and press Enter to send:");
      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(localPort);
      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());
         }
      }
   }
}

Result


Related Tutorials