Receive from UDP socket and send data back

I am trying to write a console application that accepts a request (size should be 18 bytes) and then send something (size 7 bytes) back to the client. I can't seem to get this to work. I can get the data ok, but the data I send back never reaches the client.

Here is my code

 static void Main(string[] args)
 {
        // Data to return
        byte[] ret = { 0xfe, 0xfd, 0x09, 0x00, 0x00, 0x00, 0x00 };

        // tell the user that we are waiting
        Console.WriteLine("Waiting for UDP Connection...");

        // Create a new socket to listen from
        Socket Skt = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        Skt.EnableBroadcast = true;
        Skt.Bind(new IPEndPoint(IPAddress.Loopback, 27900));

        try
        {
            // Blocks until a message returns on this socket from a remote host.
            Byte[] receiveBytes = new byte[48];
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint senderRemote = (EndPoint)sender;

            Skt.ReceiveFrom(receiveBytes, ref senderRemote);
            string returnData = Encoding.UTF8.GetString(receiveBytes).Trim();

            Console.WriteLine("This is the message you received " + returnData.ToString());

            // Sent return data
            int sent = Skt.SendTo(ret, senderRemote);
            Console.WriteLine("Sent {0} bytes back", sent);
            Skt.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.ReadLine();
    }

      

Can anyone give me some pointers?

+3


source to share


2 answers


Without seeing your client's code, it's hard to be sure where the problem might be. I can give you a working solution using the networkcomms.net networking library . The server code will look like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NetworkCommsDotNet;

namespace UPDServer
{
    class Program
    {
        static void Main(string[] args)
        {
            NetworkComms.AppendGlobalIncomingPacketHandler<string>("Message", (packetHeader, connection, incomingString) => 
            {
                Console.WriteLine("This is the message you received " + incomingString);
                connection.SendObject("Message", incomingString + " relayed by server.");
            });

            UDPConnection.StartListening(true);

            Console.WriteLine("Server ready. Press any key to shutdown server.");
            Console.ReadKey(true);
            NetworkComms.Shutdown();
        }
    }
}

      

And for the client:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NetworkCommsDotNet;

namespace UDPClient
{
    class Program
    {
        static void Main(string[] args)
        {
            string messageToSend = "This is a message To Send";
            string messageFromServer = UDPConnection.GetConnection(new ConnectionInfo("127.0.0.1", 10000), UDPOptions.None).SendReceiveObject<string>("Message", "Message", 2000, messageToSend);
            Console.WriteLine("Server said '{0}'.", messageFromServer);

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey(true);
            NetworkComms.Shutdown();
        }
    }
}

      

You will obviously need to download the NetworkCommsDotNet DLL from the website so you can add it to the "using NetworkCommsDotNet" link. Also see the server IP in the example client is currently "127.0.0.1", this should work if you started the server and client on the same machine. For more information, visit the Getting Started or How to Create a Client Server Application article.

-2


source


Here is some sample code that I modified and you can see what you can send and receive from this example. The Test method acts like a client, which could be a different process, now I made it in different threads for simulating.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Data to return
        byte[] ret = { 0xfe, 0xfd, 0x09, 0x00, 0x00, 0x00, 0x00 };

        // tell the user that we are waiting
        Console.WriteLine("Waiting for UDP Connection...");

        // Create a new socket to listen from
        Socket Skt = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        Skt.EnableBroadcast = true;
        Skt.Bind(new IPEndPoint(IPAddress.Loopback, 27900));

        try
        {
            // Blocks until a message returns on this socket from a remote host.
            Byte[] receiveBytes = new byte[48];
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint senderRemote = (EndPoint)sender;

            Thread thr = new Thread(new ThreadStart(Test));
            thr.Start();
            Skt.ReceiveFrom(receiveBytes, ref senderRemote);
            string returnData = Encoding.UTF8.GetString(receiveBytes).Trim();

            Console.WriteLine("This is the message you received " + returnData.ToString());

            // Sent return data
            int sent = Skt.SendTo(ret, senderRemote);
            Console.WriteLine("Sent {0} bytes back", sent);
            Skt.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.ReadLine();

        }



        public static void Test()
        {
            byte[] ret = { 0xfe, 0xfd, 0x09, 0x00, 0x00, 0x00, 0x00 };
            Socket Skt = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            Skt.EnableBroadcast = true;
            IPEndPoint test=new IPEndPoint(IPAddress.Loopback, 27900);

            int sent = Skt.SendTo(ret, test);
            try
            {
                // Blocks until a message returns on this socket from a remote host.
                Byte[] receiveBytes = new byte[48];
                IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint senderRemote = (EndPoint)sender;

                Skt.ReceiveFrom(receiveBytes, ref senderRemote);
                string returnData = Encoding.UTF8.GetString(receiveBytes).Trim();

                Console.WriteLine("This is the message you received " + returnData.ToString());

                // Sent return data
                //int sent = Skt.SendTo(ret, senderRemote);
                Console.WriteLine("Sent {0} bytes back", sent);
                Skt.Close();



            }
            catch (Exception ex)
            {
            }
        }

    }
}

      

+1


source







All Articles