UDP 多播.C# [英] UDP multicasting. C#

查看:79
本文介绍了UDP 多播.C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试向群组的所有成员发送消息.发件人:

I try to send message to all members of the group. Sender:

// 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! 后没有停止?我该如何解决这些问题?

I don't uderstand why there is a lot of free space between messages when I print them to screen on the client side? Why loop in the Receiver program doesn't stop after receiveing message Bye!? How can I fix this problems?

非常感谢!

推荐答案

Socket.Receive() 返回接收到的字节 你应该使用返回值来生成字符串,否则你会得到一个长度为 1024 的字符串并进行 Trim处理不了.

Socket.Receive() return the bytes received you should use the return value to generate the string, or you will get a string with the length of 1024 and Trim cannot handle it.

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

这篇关于UDP 多播.C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆