【问题标题】:UDP Listener respond to clientUDP Listener 响应客户端
【发布时间】:2012-01-06 15:17:48
【问题描述】:

我在 MSDN 上为 UDP 客户端/服务器连接找到了这个很棒的代码,但是客户端只能发送到服务器,它不能回复。我怎样才能做到这一点,以便服务器可以响应发送消息的客户端。 服务器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Security.Cryptography;


namespace UDP_Server
{
    class Program
    {
        private const int listenPort = 11000;

        private static void StartListener()
        {
            bool done = false;

            UdpClient listener = new UdpClient(listenPort);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
            try
            {
                while (!done)
                {
                    Console.WriteLine("Waiting for broadcast");
                    byte[] bytes = listener.Receive(ref groupEP);
                    Console.WriteLine("Received broadcast from {0} :\n {1}\n",groupEP.ToString(), Encoding.ASCII.GetString(bytes, 0, bytes.Length));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                listener.Close();
            }
        }

        public static int Main()
        {
            StartListener();

            return 0;
        }
    }

}

还有客户

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Security.Cryptography;

namespace UDP_Client
{
    class Program
    {
        static void Main(string[] args)
        {
            Send("TEST STRING");
            Console.Read();
        }
        static void Send(string Message)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPAddress broadcast = IPAddress.Parse("10.1.10.117");
            byte[] sendbuf = Encoding.ASCII.GetBytes(Message);
            IPEndPoint ep = new IPEndPoint(broadcast, 11000);
            s.SendTo(sendbuf, ep);
        }
    }
}

【问题讨论】:

    标签: c# sockets udp


    【解决方案1】:

    这是相同的代码,只是角色互换了。客户端需要监听某个端口,服务器将消息发送到客户端的端点而不是广播地址。

    【讨论】:

      【解决方案2】:

      只是反过来做。在客户端上调用StartListener,它可以像服务器一样接收udp数据。

      在您的服务器上,只需使用 clients 代码发送数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-23
        • 1970-01-01
        • 1970-01-01
        • 2015-06-21
        • 2014-01-09
        • 2018-10-07
        • 1970-01-01
        相关资源
        最近更新 更多