using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace NBC.Test.ObjectModel
{
/// <summary>
/// 组播通信类
/// </summary>
public class SocketUDP
{
/// <summary>
/// 组播模式发送信息
/// </summary>
/// <param name="obj"></param>
public void SendMessage(object obj)
{
//定义消息格式
//日期_/时间_/活动时长_/指标_/出课教师_/班级_/学科_/课题_/ClassID
ActivityObject mess = ((OperateObject)obj).AcObject;//此代码是我自定义的消息对象,使用时可按照自己需求从新定义
IPAddress GroupAddress = IPAddress.Parse("234.168.100.2"); //此IP值为固定区间 详情请查询msdn
int GroupPort = 11000;
UdpClient sender = new UdpClient();
IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort);
sender.EnableBroadcast = true;
try
{
byte[] bytes = UTF8Encoding.UTF8.GetBytes(mess.Date + "_/" + mess.Time + "_/" + mess.ActivityLength + "_/" + mess.Index + "_/" + mess.Techer + "_/" + mess.Grade + "_/" + mess.Subject + "_/" + mess.Project + "_/" + mess.ClassID);
sender.Send(bytes, bytes.Length, groupEP);
//sender.Close();
}
catch
{
}
}
//创建一个UdpClient实例
private Socket udpReceive;
/// <summary>
/// 接收组播信息
/// </summary>
private void ReceiveMessage()
{
try
{
string maddress = "234.168.100.2";
int listenport = 11000;
string localip = getIPAddress();
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(localip), listenport);
udpReceive = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
EndPoint ep = (EndPoint)ipe;
udpReceive.Bind(ipe);
udpReceive.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(maddress)));
while (true)
{
byte[] b = new byte[1024];
udpReceive.ReceiveFrom(b, ref ep);
string str = UTF8Encoding.UTF8.GetString(b);
string message = "来自" + ep.ToString() + "消息";
//DialogResult res = MessageBox.Show(str, message);
}
}
catch (Exception ex)
{
}
}
/// <summary>
/// 获取本地IP
/// </summary>
/// <returns></returns>
private string getIPAddress()
{
// 获得本机局域网IP地址
IPAddress[] AddressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
if (AddressList.Length < 1)
{
return "";
}
return AddressList[0].ToString();
}
}
}