UdpClient Sending

In this chapter you will learn:

  1. How to send data with UdpClient
  2. Binary UdpClient: send binary data to Udp server

Setup UdpClient and send

using System;//from  j  ava  2s  .  co m
using System.Net;
using System.Net.Sockets;
using System.Text;

class MainClass
{
   public static void Main()
   {
      UdpClient sock = new UdpClient();
      IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
      byte[] data = Encoding.ASCII.GetBytes("This is a test message");
      sock.Send(data, data.Length, iep);
      sock.Close();
   }
}

Binary UdpClient

using System;/*from   j  a  v a  2s.  co m*/
using System.Net;
using System.Net.Sockets;
using System.Text;

class MainClass
{
   public static void Main()
   {
      byte[] data = new byte[1024];
      string stringData;
      UdpClient server = new UdpClient("127.0.0.1", 9050);

      IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);

      int test1 = 45;
      double test2 = 3.14159;
      int test3 = -1234567890;
      bool test4 = false;
      string test5 = "This is a test.";

      byte[] data1 = BitConverter.GetBytes(test1);
      server.Send(data1, data1.Length);

      byte[] data2 = BitConverter.GetBytes(test2);
      server.Send(data2, data2.Length);

      byte[] data3 = BitConverter.GetBytes(test3);
      server.Send(data3, data3.Length);

      byte[] data4 = BitConverter.GetBytes(test4);
      server.Send(data4, data4.Length);

      byte[] data5 = Encoding.ASCII.GetBytes(test5);
      server.Send(data5, data5.Length);

      server.Close();
   }
}

Next chapter...

What you will learn in the next chapter:

  1. Create Uri and print out properties
Home » C# Tutorial » Network
Cookie
CredentialCache
HostEntry
IPHostEntry
IP address from host name
IPEndPoint from IPAddress
IPEndPoint Port
IPEndPoint properties
IPHostEntry
IP Address Parser
Predefined IP Address
NetworkCredential
Ping
Udp Client
Socket connection
Socket creation
Socket sendTo
TcpClient
TcpListener
UdpClient Receive
UdpClient Sending
Uri
WebClient
Response Headers
WebProxy
WebRequest