使用udp
【独立的类】
public static bool SendMessage(_ip_msg1 pMsg,string host,int port)
{
try
{
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
try
{
c.Connect(ipe);//尝试连接
}
//处理参数为空引用异常
catch (ArgumentNullException ae)
{
Console.WriteLine("ArgumentNullException : {0}", ae.ToString());
}
//处理操作系统异常
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
byte[] bb = StructToBytes(pMsg);
c.Send(bb);
System.Threading.Thread.Sleep(300);
c.Close();
}
catch (ArgumentNullException er)
{
Console.WriteLine("ArgumentNullException: {0}", er);
return false;
}
catch (SocketException er)
{
Console.WriteLine("SocketException: {0}", er);
return false;
}
//Console.WriteLine("Press Enter to Exit");
//Console.ReadLine();
return true;
}
public static byte[] StructToBytes(object structObj)
{
//int size = Marshal.Size
int size = Marshal.SizeOf(structObj);
byte[] bytes = new byte[size];
IntPtr structPtr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(structObj, structPtr, false);
Marshal.Copy(structPtr, bytes, 0, size);
//Marshal.FreeHGlobal(structPtr);
return bytes;
}
///
/// _ip_msg1这个类
///
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct _ip_msg1
{
public byte ntype; //消息类型
byte ntype1; //消息类型1
byte nGUItype; //界面交互
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
byte[] nIP; //目标IP
public byte nLen; //消息长度
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
public byte[] nBuf;
byte Reserve; //预留
}
【后台】
在事件中调用这个方法
add1、add2分别代表设备节点和设备地址
cc代表状态
public bool accCltFunc(string add1, string add2, string cc)
{
bool cat = false;
if (string.IsNullOrEmpty(add1) || string.IsNullOrEmpty(add2) || string.IsNullOrEmpty(cc))
return false;
try
{
_ip_msg1 pMsg = new _ip_msg1();
pMsg.ntype = Convert.ToByte(msg_type.NET_OUT_DOOR);
pMsg.nBuf = new byte[256];
//要接收的字节
pMsg.nBuf[2] = 0xD2;
pMsg.nBuf[3] = Convert.ToByte(add1);
pMsg.nBuf[4] = Convert.ToByte(add2);
pMsg.nBuf[5] = Convert.ToByte(cc);
pMsg.nBuf[6] = Convert.ToByte(pMsg.nBuf[2] + pMsg.nBuf[3] + pMsg.nBuf[4] + pMsg.nBuf[5]);
cat = PublicCLSS.SendMessage(pMsg, "192.168.0.250", 8088);
cat= PublicCLSS.SendMessage(pMsg, "127.0.0.1", 8088);
if (!cat)
{
return cat;
}
else
{
return cat;
}
}
catch (ArgumentNullException er)
{
Console.WriteLine("ArgumentNullException: {0}", er);
return false;
}
catch (SocketException er)
{
Console.WriteLine("SocketException: {0}", er);
return false;
}
}
基本就是这些!