c# udp 组播

c# udp 组播

一个发送线程发送组播消息,一个接收线程接收消息

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace multicasttest
{
class Program
{
static string multiCastIp = "224.1.1.1";
static int port = 60000;

static void Main(string[] args)
{
Socket s; //socket对象
IPEndPoint iep; //ip对象
EndPoint ep; //ep对象

s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
iep = new IPEndPoint(IPAddress.Parse(multiCastIp), port);
ep = (EndPoint)iep;

string msg = "hello";
byte[] buf = Encoding.Default.GetBytes(msg);


Thread t = new Thread(new ThreadStart(RecvThread));
t.IsBackground = true;
t.Start();
///

while (true)
{
s.SendTo(buf, ep);
Thread.Sleep(1000);
}

}

static void RecvThread()
{
Socket rec_s; //socket对象
IPEndPoint rec_iep; //ip对象
EndPoint rec_ep; //ep对象

rec_s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
rec_iep = new IPEndPoint(IPAddress.Any, port);
rec_ep = (EndPoint)rec_iep;

rec_s.Bind(rec_iep);
rec_s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(multiCastIp)));
while (true)
{
byte[] buf = new byte[50];
//判断接收到的数据流大小
int len = rec_s.ReceiveFrom(buf, ref rec_ep);
string msg = Encoding.Default.GetString(buf);
Console.WriteLine(msg);
}
}

}
}

你可能感兴趣的:(c#,udp,组播)