UDP传输一个类的问题
定义的一个类:
[Serializable]
struct tagMonitorMessage
{
public ulong m_message_length;
char[] key;
char m_system;
char m_command;
char[] monitor_content;
char[] reserver;
public static byte[] Serialize(object obj)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
bf.Serialize(stream, obj);
byte[] datas = stream.ToArray();
stream.Dispose();
return datas;
}
public static object Deserialize(byte[] datas)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream stream = new MemoryStream(datas);
object obj = bf.Deserialize(stream);
stream.Dispose();
return obj;
}
}
发送时
private void button1_Click(object sender, EventArgs e)
{
tagMonitorMessage mm = new tagMonitorMessage();
mm.m_message_length = 1223112;
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress broadcast = IPAddress.Parse(this.textBox2.Text.ToString());
// byte[] sendbuf = Encoding.GetEncoding("gb2312").GetBytes(this.textBox1.Text.ToString());
byte[] sendbuf = tagMonitorMessage.Serialize(mm);
IPEndPoint ep = new IPEndPoint(broadcast, 11000);
s.SendTo(sendbuf, ep);
}
没有问题
但在服务器端接收时
private void StartListener()
{
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
try
{
while (!done)
{
byte[] bytes = listener.Receive(ref groupEP);
string strIP;
strIP = "信息来源" + groupEP.Address.ToString();
tagMonitorMessage mm = (tagMonitorMessage)tagMonitorMessage.Deserialize(bytes);
MessageBox.Show(mm.ToString(), strIP);
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), "Wrong!");
}
finally
{
listener.Close();
}
}
到红色标记进入类中的方法Deserialize
运行到
object obj = bf.Deserialize(stream);
报错:
无法找到程序集"UDPClient,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null".
请各位指点!
------解决方案--------------------又是协议,看看3个钟头的协议这块,头都大了,现在又遇见了.......
不太想看了,不好意思
帮你顶一下吧,留给后来人给个好的解答
------解决方案--------------------tagMonitorMessage mm = (tagMonitorMessage)tagMonitorMessage.Deserialize(bytes);
报什么错 这种写法如果数据没问题的话应该是不会出错的
------解决方案--------------------
建议楼主使用WCF来实现传递对象
可以看下这个频道的文章:
WCF
------解决方案--------------------把你的类单独做成一个项目,编译为DLL
然后客户端和服务端分别引用这个DLL