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();
Receiver:
// 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;
}
}
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?
Thank you very much!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…