从UDP套接字接收并发回数据

时间:2013-02-02 02:25:41

标签: c# sockets udp

我正在尝试编写一个接受请求的控制台应用程序(大小为18个字节),然后将一些内容(大小为7个字节)发送回客户端。我为我的生活似乎无法让这个工作。我可以很好地接收数据,但我发回的数据永远不会到达客户端。

这是我的代码

 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();
    }

有人给我一些指示吗?

2 个答案:

答案 0 :(得分:2)

以下是我修改过的示例代码,您可以看到可以从此示例接收和发送。方法测试作为客户端,可以是一个不同的过程,现在我已经在不同的线程中进行模拟。

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 :(得分:-2)

如果没有看到您的客户端代码,很难确定问题可能在哪里。我可以使用network library networkcomms.net为您提供有效的解决方案。服务器的代码如下:

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();
        }
    }
}

对于客户:

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();
        }
    }
}

您显然需要从网站下载NetworkCommsDotNet DLL,以便您可以在“使用NetworkCommsDotNet”参考中添加它。另请参阅客户端示例中的服务器IP地址当前为“127.0.0.1”,如果您在同一台计算机上同时运行服务器和客户端,这应该可以工作。有关详细信息,请查看getting startedhow to create a client server application文章。