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();
}
}
}