Click here to Skip to main content
15,881,812 members
Articles / General Programming
Tip/Trick

Send/Receive classes through UDP

Rate me:
Please Sign up or sign in to vote.
4.88/5 (5 votes)
26 Jul 2012CPOL2 min read 55.6K   4.2K   21   6
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)


Written By
Software Developer (Senior)
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionmatlab Pin
Member 1227157518-Jan-16 6:05
Member 1227157518-Jan-16 6:05 
QuestionManual serialization Pin
John Brett26-Jul-12 22:45
John Brett26-Jul-12 22:45 
QuestionFollowing on from Paulo's comments Pin
Richard MacCutchan13-Jul-12 5:42
mveRichard MacCutchan13-Jul-12 5:42 
AnswerRe: Following on from Paulo's comments Pin
Amir Hesami19-Jul-12 13:06
Amir Hesami19-Jul-12 13:06 
In some cases such as sending video or audio packets, it's better to use UDP
GeneralRe: Following on from Paulo's comments Pin
John Brett26-Jul-12 22:37
John Brett26-Jul-12 22:37 
GeneralI didn't vote, but... Pin
Paulo Zemek13-Jul-12 3:38
mvaPaulo Zemek13-Jul-12 3:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.