Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming

Send/Receive classes through UDP

4.88/5 (5 votes)
26 Jul 2012CPOL2 min read 57.1K   4.2K  
A library which can get any class you pass to it, convert it to bytes, and send it to the other end.

Introduction 

I was involved with a project which had couple of developers working on and they needed to send their classes through UDP between clients. I ended up writing this library which can get any class you pass to it, convert it to bytes, and send it to the other end. The Receiving end then can convert it back to the class they want and process the data. This library needed to be simple for other developers to use.

Using the code

The code is very easy to use, it has two classes:

  • An abstract class called Message.
  • A UDP client/server called client.

You need to create your own message class which inherits from the abstract class in the library. The class diagram for this abstract class is as below:

Image 1

There are two properties for all messages in this class.A MessageID which is a GuID and timeStamp is when the message is created. Public methods that can be called are ToMessage and ToByte which convert message class to byte or to the class instance respectively.

I have createa sample message class in the demo which is called 'testMessage' which has 3 fields.

C++
public class testMessage:UDPTalkChannel.Message
{
    public string userName;
    public int ID;
    public string textMessage;

    public testMessage()
    {
    }
}

You can create your own message class and have as many fields or properties as you like.

The client class diagram is as shown below:

Image 2

You need to set these fields from the constructor:

  • serverIP
  • outgoingPort
  • IncomingPort
  • Buffersize

Incoming port is the port the client is bound to and keeps listening for receiving messages. Outgoing port is the port client sends data out and the server IP is the destination IP address which the messages are sent to. Buffer size is the size of the allocated buffer which is filled with received data, you need to have the same buffer size on both ends. Also please note that if the data your are sending is larger then what UDP protocol can handle it will fail, so you are responsible for breaking your data into smaller packets. There are 3 events which are raised and you can define them in your code, onError, onReceived, and onSent. Here is the definition of client in the demo code.

C++
private void btnInit_Click(object sender, EventArgs e)
{
  client = new UDPTalkChannel.Client(txtRemoteIP.Text, Convert.ToInt32(txtOutPort.Text), 
               Convert.ToInt32(txtInPort.Text), Convert.ToInt32(txtBufferSize.Text));
  client.onSent += new UDPTalkChannel.Client.SentEventHandler(client_onSent);
  client.onError += new UDPTalkChannel.Client.ErrorEventHandler(client_onError);
  client.onReceived += new UDPTalkChannel.Client.ReceivedEventHandler(client_onReceived);
}
C++
void client_onReceived(object sender, UDPTalkChannel.Client.ReceivedEventArgs e)
{
   testMessage tstMsg = new testMessage();
   tstMsg = (testMessage)tstMsg.ToMessage(e.MessageByte);
 
   string strTem = string.Format("Received: {0}, from: {1}, ID: {2}, IP: {3}", 
                   tstMsg.textMessage, tstMsg.userName, tstMsg.ID, e.senderClient.ToString());

   MessageBox.Show(strTem);
}
 
void client_onError(object sender, UDPTalkChannel.Client.ErrorEventArgs e)
{
    MessageBox.Show(e.Ex.Message, "Error");
}
 
void client_onSent(object sender, UDPTalkChannel.Client.SentEventArgs e)
{
    MessageBox.Show("Message Sent");
}

Messages are converted back from byte to the testMessage class in onReceived event and displayed. You can send a message by converting the class to byte and pass it to send method from the client class:

C++
private void btnSend_Click(object sender, EventArgs e)
{
   testMessage tstMsg = new testMessage()
   {
       userName=txtUsername.Text,
       ID=Convert.ToInt32(txtID.Text),
       textMessage=txtMessage.Text
   };
   client.Send(tstMsg.ToByte());
}

Run two instances of the demo program and initialise them first, please note if you are running both ends on same machine, set different incoming and outgoing ports. Click init button first to initialise clients and then you can start sending messages.

Image 3

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)