Posts Tagged ‘ User Datagram Protocol ’

Raw UDP Adapter – Listener

My previous blog I showed how easy it is to create a UDP broadcast adapter.  The problem with using the soap.udp adapter is that the message is wrapped in a soap envelope.  I tried various way in vain to get around the soap envelope so that I can broadcast or receive messages without the extra fat.  Although for most part it soap envelope would not matter, but just for kicks, I wanted to receive data without soap, I decided to write an adapter.

I followed this tutorial (echo adapter) and made the following changes to include socket connections.  On initialization, I create and bind the socket to the ip and port

listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
localEndPoint = new IPEndPoint(IPAddress.Parse(RemoteAddress), RemotePort);
listener.Bind(localEndPoint);
endpoint = (EndPoint) localEndPoint;

On background worker, I open the connection and start listening.

if (IsConnected)
{
   ReceiveStarted = true;
   while (!StopReciving)
   {
      byte[] data = new byte[1024];
      int receive = listener.ReceiveFrom(data, ref endpoint);
      var receivedData = Encoding.ASCII.GetString(data, 0, receive);
      lock (inboundQueueSynchronizationLock)
      {
          Message requestMessage = Message.CreateMessage(MessageVersion.Default, "UDP/Data",
                                                                       receivedData);
          InboundQueue.Enqueue(requestMessage);
       }
    }
}

And basically thats all. Download the full code here.  The zip file includes the code and projects for setup and custom action.

Advertisements