UDP multicasting. C#

本文关键字:multicasting UDP | 更新日期: 2023-09-27 18:05:11

我试着给组里的所有成员发消息。发送者:

// Create socket
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        // Multicast IP-address
        IPAddress ip = IPAddress.Parse("224.168.55.25");
        // Join multicast group
        s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip));
        // TTL
        s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 2);
        // Create an endpoint
        IPEndPoint ipep = new IPEndPoint(ip, 4567);
        // Connect to the endpoint
        s.Connect(ipep);
        // Scan message
         while (true)
        {
            byte[] buffer = new byte[1024];
            string msg = Console.ReadLine();
            buffer = Encoding.ASCII.GetBytes(msg);
            s.Send(buffer, buffer.Length, SocketFlags.None);
            if (msg.Equals("Bye!", StringComparison.Ordinal))
                break;
        }
        // Close socket
        s.Close();

接收机:

// Create new socket
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        // Create IP endpoint
        IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 4567);
        // Bind endpoint to the socket
        s.Bind(ipep);
        // Multicast IP-address
        IPAddress ip = IPAddress.Parse("224.168.55.25");
        // Add socket to the multicast group
        s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
        // Receive messages
        while (true)
        {
            byte[] data = new byte[1024];
            s.Receive(data);
            string str = System.Text.Encoding.ASCII.GetString(data, 0, data.Length);
            Console.WriteLine(str.Trim());
            if (str.Equals("Bye!", StringComparison.Ordinal))
            {
                break;
            }
        }

我不明白为什么当我在客户端打印到屏幕上时,消息之间有很多空闲空间?为什么Receiver程序中的循环在收到Bye!消息后不停止?我该如何解决这些问题?

非常感谢!

UDP multicasting. C#

您正在创建udp套接字。Udp套接字不面向连接。所以它只接收消息,不知道发送方的状态。即使发送方套接字关闭,接收方也会继续侦听。我希望我正确理解了你的问题。

if (strData.Trim().Equals("Bye!", StringComparison.Ordinal))
{
                Console.WriteLine("that's right");
                break;
}

Socket.Receive()返回接收到的字节,您应该使用返回值来生成字符串,否则您将得到一个长度为1024的字符串,Trim无法处理它。

int len = s.Receive(data);
string str = System.Text.Encoding.ASCII.GetString(data, 0, len);