Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# UDP Socket client and server

My first question here. I am new to this kind of programming, and i've only programmed .NET web sites and forms.

Now, the company I work at, asks me to make an ActiveX component, that listens to UDP messages, and turns them into events.

The UDP msgs are send from Avaya system, so i was told that to test my ActiveX, at first I need to create an app, that only sends UDP (only one button that sends pre-defined UDP string). And then create listener socket, ordinary C# app, that will get those transmitted UDP string from the tests app. Both apps will work on the same machine.

Later, when i get this working, i need to make the listener an ActiveX component, but first things first.

I need to know if there are any good tutorials about this, and any idea on how to start? I am sorry for my ignorance, but i am really new on this and i don't really have any time to learn this since it has to be done in 2 weeks.

Thanks in advance.

edit: I managed to create 2 simple console applications, and was sending UDP messages between them successfully. The sender will be only for testing, and now I need to re-make my receiver to get the UDP message and 'translate' it to events. And lastly, to make it an ActiveX control...

like image 582
Paul Avatar asked Nov 05 '13 10:11

Paul


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


2 Answers

Simple server and client:

public struct Received
{
    public IPEndPoint Sender;
    public string Message;
}

abstract class UdpBase
{
    protected UdpClient Client;

    protected UdpBase()
    {
        Client = new UdpClient();
    }

    public async Task<Received> Receive()
    {
        var result = await Client.ReceiveAsync();
        return new Received()
        {
            Message = Encoding.ASCII.GetString(result.Buffer, 0, result.Buffer.Length),
            Sender = result.RemoteEndPoint
        };
    }
}

//Server
class UdpListener : UdpBase
{
    private IPEndPoint _listenOn;

    public UdpListener() : this(new IPEndPoint(IPAddress.Any,32123))
    {
    }

    public UdpListener(IPEndPoint endpoint)
    {
        _listenOn = endpoint;
        Client = new UdpClient(_listenOn);
    }

    public void Reply(string message,IPEndPoint endpoint)
    {
        var datagram = Encoding.ASCII.GetBytes(message);
        Client.Send(datagram, datagram.Length,endpoint);
    }

}

//Client
class UdpUser : UdpBase
{
    private UdpUser(){}

    public static UdpUser ConnectTo(string hostname, int port)
    {
        var connection = new UdpUser();
        connection.Client.Connect(hostname, port);
        return connection;
    }

    public void Send(string message)
    {
        var datagram = Encoding.ASCII.GetBytes(message);
        Client.Send(datagram, datagram.Length);
    }

}

class Program 
{
    static void Main(string[] args)
    {
        //create a new server
        var server = new UdpListener();

        //start listening for messages and copy the messages back to the client
        Task.Factory.StartNew(async () => {
            while (true)
            {
                var received = await server.Receive();
                server.Reply("copy " + received.Message, received.Sender);
                if (received.Message == "quit")
                    break;
            }
        });

        //create a new client
        var client = UdpUser.ConnectTo("127.0.0.1", 32123);

        //wait for reply messages from server and send them to console 
        Task.Factory.StartNew(async () => {
            while (true)
            {
                try
                {
                    var received = await client.Receive();
                    Console.WriteLine(received.Message);
                    if (received.Message.Contains("quit"))
                        break;
                }
                catch (Exception ex)
                {
                    Debug.Write(ex);
                }
            }
        });

        //type ahead :-)
        string read;
        do
        {
            read = Console.ReadLine();
            client.Send(read);
        } while (read != "quit");
    }
}
like image 103
lboshuizen Avatar answered Sep 28 '22 04:09

lboshuizen


Simple server and client:

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

class Program
{
    static void Main(string[] args)
    {
        // Create UDP client
        int receiverPort = 20000;
        UdpClient receiver = new UdpClient(receiverPort);

        // Display some information
        Console.WriteLine("Starting Upd receiving on port: " + receiverPort);
        Console.WriteLine("Press any key to quit.");
        Console.WriteLine("-------------------------------\n");

        // Start async receiving
        receiver.BeginReceive(DataReceived, receiver);

        // Send some test messages
        using (UdpClient sender1 = new UdpClient(19999))
            sender1.Send(Encoding.ASCII.GetBytes("Hi!"), 3, "localhost", receiverPort);
        using (UdpClient sender2 = new UdpClient(20001))
            sender2.Send(Encoding.ASCII.GetBytes("Hi!"), 3, "localhost", receiverPort);

        // Wait for any key to terminate application
        Console.ReadKey();
    }

    private static void DataReceived(IAsyncResult ar)
    {
        UdpClient c = (UdpClient)ar.AsyncState;
        IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);

        // Convert data to ASCII and print in console
        string receivedText = ASCIIEncoding.ASCII.GetString(receivedBytes);
        Console.Write(receivedIpEndPoint + ": " + receivedText + Environment.NewLine);

        // Restart listening for udp data packages
        c.BeginReceive(DataReceived, ar.AsyncState);
    }
}
like image 21
Bachor Avatar answered Sep 28 '22 04:09

Bachor