close
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

using YD.ZYCAlarm.Buffer;

namespace YD.ZYCAlarm.UDPCommunicate


{

/**//// <summary>
/// SendCommand 的摘要說明。
/// </summary>
public class SendCommand

{

/**//// <summary>
/// 要發送的命令文本
/// </summary>
private string m_CmdText;


/**//// <summary>
///
/// </summary>
private static readonly int BUF_SIZE=0x10000;


/**//// <summary>
/// 本地UDP對像
/// </summary>
private Socket m_Client ;


/**//// <summary>
/// 本地端口(也可以不設)
/// </summary>
private int m_LocalPort;


/**//// <summary>
/// 遠程端口
/// </summary>
private int m_RemotePort ;


/**//// <summary>
/// 遠程IP
/// </summary>
private string m_RemoteIP ;


/**//// <summary>
/// 對方網絡節點
/// </summary>
private IPEndPoint m_RemoteEP ;

public SendCommand( string strIP,int iPort,string strCmd )

{
this.m_RemoteIP = strIP ;
this.m_RemotePort = iPort;
this.m_CmdText = strCmd;

m_RemoteEP = new IPEndPoint(IPAddress.Parse( m_RemoteIP ) , m_RemotePort) ;
}

private void ConnectToServer()

{
m_Client=new Socket(AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp
);

m_Client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout,
3000
);
}

public bool Send()

{
ConnectToServer();
try

{
Byte[] sendBytes = Encoding.ASCII.GetBytes(this.m_CmdText);
this.m_Client.SendTo(sendBytes ,sendBytes.Length,SocketFlags.None,m_RemoteEP) ;

//接收服務端的回應的成功信息
return Receive();
}
catch

{
return false ;
}
}

private bool Receive()

{
byte[] buf=new byte[BUF_SIZE];
EndPoint remoteEndPoint=new IPEndPoint(IPAddress.Any,0);
try

{
int receive = this.m_Client.ReceiveFrom(buf,ref remoteEndPoint) ;
string strData= Encoding.ASCII.GetString(buf,0,receive);

if(strData == "OK")

{
return true ;
}
else

{
return false ;
}
}
catch

{
return false ;
}
finally

{
this.m_Client.Close();
this.m_Client = null ;
}
}

public void Dispose()

{
if(this.m_Client != null)

{
this.m_Client.Close();
this.m_Client = null;
}
}

}
}











































































































































































全站熱搜