Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a UDP Server in C#? [duplicate]

Tags:

c#

udp

Possible Duplicate:
C# How to make a simple UDP server

I want to make a UDP server in C#. How do I do that? How can I customize which port it listens on (namely 1212)?

like image 861
Saeed Avatar asked Jan 30 '11 18:01

Saeed


People also ask

How do I create a UDP socket?

The steps of establishing a UDP socket communication on the server side are as follows: Create a socket with the socket() function; Bind the socket to an address using the bind() function; Send and receive data by means of recvfrom() and sendto().

What is a UDP server?

User Datagram Protocol (UDP) is a communications protocol that is primarily used to establish low-latency and loss-tolerating connections between applications on the internet. UDP speeds up transmissions by enabling the transfer of data before an agreement is provided by the receiving party.


1 Answers

Here is a sample in C#:

/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class UdpSrvrSample
{
   public static void Main()
   {
      byte[] data = new byte[1024];
      IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
      UdpClient newsock = new UdpClient(ipep);

      Console.WriteLine("Waiting for a client...");

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

      data = newsock.Receive(ref sender);

      Console.WriteLine("Message received from {0}:", sender.ToString());
      Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length));

      string welcome = "Welcome to my test server";
      data = Encoding.ASCII.GetBytes(welcome);
      newsock.Send(data, data.Length, sender);

      while(true)
      {
         data = newsock.Receive(ref sender);

         Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length));
         newsock.Send(data, data.Length, sender);
      }
   }
}
like image 193
George Stocker Avatar answered Sep 18 '22 18:09

George Stocker