有谁能给我一段C# 组播的代码。或是一些资料
发送和接收的。我整了好多天也没弄出来 下边是我写的代码。
//Send
private void SendMessage(string str)
{
byte[] message = Encoding.Unicode.GetBytes(str);
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress ip = IPAddress.Parse("224.0.0.1");
try
{
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip));
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 5);
}
catch (Exception e)
{
this.Text = e.Message;
//无效的参数异常,
}
IPEndPoint ipep = new IPEndPoint(ip, 7758);
s.Connect(ipep);
s.Send(message, message.Length, SocketFlags.None);
s.Close();
}
private void RecMessage()
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 7758);
s.Bind(ipep);
IPAddress ip = IPAddress.Parse("224.0.0.1");
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
while (true)
{
byte[] b = new byte[1024];
s.Receive(b);
string str = System.Text.Encoding.ASCII.GetString(b, 0, b.Length);
this.Text = str;
}
s.Close();
}
lcq1986 你好。你的代码 还像海缺一点 能给我补齐吗?
Thread thread = new Thread(new ParameterizedThreadStart(SocketHandler.OnReceiveMsg));
没有要启动的函数啊。
我正在努力调试你的程序 谢谢你的帮忙!
给你一个自己写的类.你看看就明白了.
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Windows.Forms;
using System.Threading;
namespace LanMessenger
{
public class UdpSocket
{
private static UdpClient _msgClient;
private static UdpClient _fileSendClient;
private static UdpClient _fileReceiveClient;
private static int _msgPort = 6868;
private static int _fileSendPort = 6867;
private static int _fileReceivePort = 6869;
private static IPAddress _groupIpAddress = IPAddress.Parse("224.0.0.101");
private static string _localIpAddress = "127.0.0.1";
public static string LocalIpAddress
{
get { return _localIpAddress; }
}
private static IPEndPoint _remoteEP = null;
/// <summary>
/// 初始化套接字
/// </summary>
public static void InitSocket()
{
_localIpAddress = GetLocalIpAddress();
_msgClient = new UdpClient(_msgPort);
_fileSendClient = new UdpClient(_fileSendPort);
_fileReceiveClient = new UdpClient(_fileReceivePort);
_msgClient.EnableBroadcast = true;
_msgClient.MulticastLoopback = true;
_msgClient.JoinMulticastGroup(_groupIpAddress);
}
/// <summary>
/// 获取本机IP地址
/// </summary>
/// <returns>本机的IP地址</returns>
private static string GetLocalIpAddress()
{
string ip = "127.0.0.1";
IPAddress [] ipAddresss = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ipAddress in ipAddresss)
{
ip = ipAddress.ToString();
if (ip != "127.0.0.1")
{
break;
}
}
return ip;
}
/// <summary>
/// 组播消息
/// </summary>
/// <param name="buffer">要发送的byte数组</param>
public static void SendMsgToAll(byte[] buffer)
{
try
{
_msgClient.Send(buffer, buffer.Length, new IPEndPoint(_groupIpAddress, _msgPort));
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
/// <summary>
/// 发送消息给指定机器
/// </summary>
/// <param name="buffer">要发送的byte数组</param>
/// <param name="remoteIpAddress">对方机器IP地址</param>
public static void SendMsgToOne(byte[] buffer,string remoteIpAddress)
{
try
{
_msgClient.Send(buffer, buffer.Length, new IPEndPoint(IPAddress.Parse(remoteIpAddress), _msgPort));
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
/// <summary>
/// 监听消息端口,该函数为线程函数
/// </summary>
public static void ListenMessagePort()
{
try
{
while (true)
{
byte[] buffer = _msgClient.Receive(ref _remoteEP);
Thread thread = new Thread(new ParameterizedThreadStart(SocketHandler.OnReceiveMsg));
thread.Start((object)buffer);
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
}
补充:那是我自己的处理函数.每个人的处理逻辑不一样.我给你你也用不了. 我还是附上吧.你肯定用不了.你那个地方写个线程函数来处理其实就可以了
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
namespace LanMessenger
{
public class SocketHandler
{
/// <summary>
/// 提供序列化和反序列话方法的对象
/// </summary>
private static BinaryFormatter Transfer = new BinaryFormatter();
public delegate void MessageHandler(MessageEventArgs e);
public static event MessageHandler OnUserOnline;
public static event MessageHandler OnUserOffline;
public static event MessageHandler OnUserChangeInfo;
public static event MessageHandler OnReceiveMessage;
/// <summary>
/// 将Socket接受到的byte转化成可识别的Message对象
/// </summary>
/// <param name="buffer">Socket接受到的byte</param>
private static Message ChangeByteToMessage(byte[] buffer)
{
try
{
//将加密消息转化为正常消息
byte[] decodebuffer = Kits.CryptTo.Decrypt.TripledDESDecrypt(buffer, SysConst.TriDesKey);
MemoryStream ms = new MemoryStream(decodebuffer, 0, decodebuffer.Length, true, true);
//将接收到的流反序列化为对象
object obj = Transfer.Deserialize(ms);
return (Message)obj;
}
catch (Exception err)
{
return null;
}
}
/// <summary>
/// 将Message对象转化成byte
/// </summary>
/// <param name="msg"></param>
/// <returns>转化成的byte</returns>
private static byte[] ChangeMessageToByte(Message msg)
{
MemoryStream ms = new MemoryStream();
//将消息对象序列化
Transfer.Serialize(ms, (object)msg);
byte[] buffer = ms.GetBuffer();
//进行3DES加密
byte[] encodebuffer = Kits.CryptTo.Encrypt.TripledDESEncrypt(buffer, SysConst.TriDesKey);
return encodebuffer;
}
/// <summary>
/// 启动Message监听
/// </summary>
public static void BeginListenMessage()
{
Thread thread = new Thread(new ThreadStart(UdpSocket.ListenMessagePort));
thread.Start();
}
/// <summary>
/// 接收消息处理函数
/// </summary>
/// <param name="obj"></param>
public static void OnReceiveMsg(object obj)
{
try
{
byte[] buffer = (byte[])obj;
Message msg = ChangeByteToMessage(buffer);
MessageTypeHandler(msg);
}
catch (Exception err)
{
return;
}
}
/// <summary>
/// 消息分类函数
/// </summary>
/// <param name="msg">Socket接收到的消息</param>
private static void MessageTypeHandler(Message msg)
{
switch (msg.Protrol)
{
case ProtrolType.GetOnline: UserOnlineHandler(msg);
break;
case ProtrolType.GetOffine: UserOfflineHandler(msg);
break;
case ProtrolType.ChangeUserInfo: ChangeUserInfoHandler(msg);
break;
case ProtrolType.SendMessage: GetMessageHandler(msg);
break;
default: throw new Exception("An Unknow Message Protrol Received!");
}
}
private static void UserOnlineHandler(Message msg)
{
MessageEventArgs e = new MessageEventArgs(msg);
OnUserOnline(e);
}
private static void UserOfflineHandler(Message msg)
{
MessageEventArgs e = new MessageEventArgs(msg);
OnUserOffline(e);
}
private static void ChangeUserInfoHandler(Message msg)
{
MessageEventArgs e = new MessageEventArgs(msg);
OnUserChangeInfo(e);
}
private static void GetMessageHandler(Message msg)
{
MessageEventArgs e = new MessageEventArgs(msg);
OnReceiveMessage(e);
}
/// <summary>
/// 组播消息
/// </summary>
/// <param name="msg">要发送的消息</param>
public static void SendMessageToAll(Message msg)
{
byte[] buffer = ChangeMessageToByte(msg);
UdpSocket.SendMsgToAll(buffer);
}
/// <summary>
/// 发消息给指定IP
/// </summary>
/// <param name="msg">消息体</param>
/// <param name="ip">对方IP</param>
public static void SendMessageToOne(Message msg,string ip)
{
byte[] buffer = ChangeMessageToByte(msg);
UdpSocket.SendMsgToOne(buffer,ip);
}
}
public class MessageEventArgs : EventArgs
{
public Message message;
public MessageEventArgs()
{
}
public MessageEventArgs(Message msg)
{
this.message = msg;
}
}
}