using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Text; using System.Windows.Forms; using System.Xml;namespace SjcyCB.controlcs { /// <summary> /// ypCommunication 的摘要说明。 /// </summary> public class ypCommunication { /// <summary> /// 变量 /// </summary> public short _CommPort=1;//串口号 public bool _CommDisConnEn=false;//启动监听串口猫断开 public bool _CommConnEn=false;//是否启动监听串口描连接 public bool _netListen=false; //是否监听 private bool _CheckIpServer=true;//是否检测IP服务器连接 private string _GprsID=""; private bool _GprsEn=false;//当前GPRS连接是否为真
/// <summary> /// 类实例 /// </summary> public AxMSCommLib.AxMSComm axMSComm;//串口控件实例 public Socket listener;//监听 socket public Socket socketA=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); //向外连接 socket private Socket socketIP=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); //连接IP服务器的socket private Thread mythread;//监视socket等待连接的线程 private Socket newSocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); //listen应答socket private Thread newthread=null;//listen连接后等待数据的线程 private Thread threadA=null;//socketA连接后等待数据的线程 private Thread threadIP=null;//监视与IP服务器的线程 /// <summary> /// 声明代表类型 /// </summary> public delegate void EventHandler(byte[] newbyte);//声明代表 //public delegate void cEventHandler(); public delegate void cEventHandler();//声明代表,无参数 public delegate void sEventHandler(string ctype);//声明代表,返回字符参数 /// <summary> /// 声明事件 /// </summary> public event cEventHandler EvenConnIpServer;//IP服务器连接失败事件 public event cEventHandler EvenDisIpServer;//IP服务器连接成功事件 public event sEventHandler NetConn;//listen网络连接成功事件 public event sEventHandler NetDisConn;//listen网络连接断开事件 public event cEventHandler NetDotConn;//向外连接失败事件 public event EventHandler NetDataRev;//listen网络数据到来事件
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Windows.Forms;
using System.Xml;namespace SjcyCB.controlcs
{
/// <summary>
/// ypCommunication 的摘要说明。
/// </summary>
public class ypCommunication
{
/// <summary>
/// 变量
/// </summary>
public short _CommPort=1;//串口号
public bool _CommDisConnEn=false;//启动监听串口猫断开
public bool _CommConnEn=false;//是否启动监听串口描连接
public bool _netListen=false; //是否监听
private bool _CheckIpServer=true;//是否检测IP服务器连接
private string _GprsID="";
private bool _GprsEn=false;//当前GPRS连接是否为真
/// <summary>
/// 类实例
/// </summary>
public AxMSCommLib.AxMSComm axMSComm;//串口控件实例
public Socket listener;//监听 socket
public Socket socketA=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); //向外连接 socket
private Socket socketIP=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); //连接IP服务器的socket
private Thread mythread;//监视socket等待连接的线程
private Socket newSocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); //listen应答socket
private Thread newthread=null;//listen连接后等待数据的线程
private Thread threadA=null;//socketA连接后等待数据的线程
private Thread threadIP=null;//监视与IP服务器的线程 /// <summary>
/// 声明代表类型
/// </summary>
public delegate void EventHandler(byte[] newbyte);//声明代表
//public delegate void cEventHandler();
public delegate void cEventHandler();//声明代表,无参数
public delegate void sEventHandler(string ctype);//声明代表,返回字符参数 /// <summary>
/// 声明事件
/// </summary>
public event cEventHandler EvenConnIpServer;//IP服务器连接失败事件
public event cEventHandler EvenDisIpServer;//IP服务器连接成功事件
public event sEventHandler NetConn;//listen网络连接成功事件
public event sEventHandler NetDisConn;//listen网络连接断开事件
public event cEventHandler NetDotConn;//向外连接失败事件
public event EventHandler NetDataRev;//listen网络数据到来事件
public ypCommunication(AxMSCommLib.AxMSComm _axMSComm)
{
//
// TODO: 在此处添加构造函数逻辑
//
axMSComm=_axMSComm;
_CommPort=XmlGetCommPort();
} #region 公用的函数,内部方法
/// <summary>
/// 获取本地IP
/// </summary>
/// <returns></returns>
private static IPAddress GetServerIP()
{
IPHostEntry ieh=Dns.GetHostByName(Dns.GetHostName());
return ieh.AddressList[0];
} /// <summary>
/// socket等待数据,实现socket接受数据的方法
/// </summary>
private void DataRev()
{
//测试程序,+++++++++++++++++
//if(!Form_Main.DataRev && Form_Main.SendCmdEN)
// return;
//++++++++++++++++++++++++++++
byte[] byteMessage=new byte[1024];
int intbyt=0;
while(true)
{
try
{
intbyt=newSocket.Receive(byteMessage,byteMessage.Length,0);
}
catch{} if(intbyt>0)
{
byte[] tmp=new byte[intbyt];
for(int i=0;i<intbyt;i++)
{
tmp[i]=byteMessage[i];
}
if(_GprsEn)
{
NetDataRev(tmp);
}
else
{
if(intbyt==8)
{
yFunction yf=new yFunction();
string stmp=yf.HexToString(tmp);
if(stmp.Substring(6,8)==_GprsID)
{
NetConn("c");
_GprsEn=true;
}
}
else
{
newSocket.Close();
_GprsEn=false;//GPRS连接为假
_netListen=true;
newthread.Abort();
//NetDisConn("c");
}
}
}
else
{
newSocket.Close();
_GprsEn=false;//GPRS连接为假
_netListen=true;
NetDisConn("c");
newthread.Abort();
}
//}
}
}
/// <summary>
/// socketA接收数据的方法
/// </summary>
private void DataRevA()
{
byte[] byteMessage=new byte[1024];
int intbyt=0;
while(true)
{
try
{
intbyt=socketA.Receive(byteMessage,byteMessage.Length,0);
if(intbyt>0)
{
byte[] tmp=new byte[intbyt];
for(int i=0;i<intbyt;i++)
{
tmp[i]=byteMessage[i];
}
NetDataRev(tmp);
}
else
{
socketA.Close();
NetDisConn("b");
threadA.Abort();
}
//}
}
catch{}
}
}
/// <summary>
/// 传口接收数据方法
/// </summary>
private void CommDataRev(object source,System.EventArgs ls)
{
byte[] bytTmp;
object objIn;
if(axMSComm.CommEvent == (short)MSCommLib.OnCommConstants.comEvCTS)
{//开始接受数据
objIn=axMSComm.Input;
bytTmp=(byte[])objIn;
NetDataRev(bytTmp);
}
} /// <summary>
/// 连接IP服务器的方法
/// </summary>
private void ConnIpServer()
{
try
{
IPAddress RemIP = IPAddress.Parse("219.237.88.196"); //把远程IP,string to ipaddress
IPEndPoint iep=new IPEndPoint(RemIP,5001);
//socketA.RemoteEndPoint=iep;
socketIP.Connect(iep);
try
{
byte[] btmp={0xDB,0x01,0x02,0x00,0x01,0xDF};
socketIP.Send(btmp);
}
catch
{
}
threadIP = new Thread(new ThreadStart(DataRevIP)); //创建线程
threadIP.IsBackground=true;//设置线程为后台运行
threadIP.Start();
EvenConnIpServer();//连接成功事件
}
catch
{
EvenDisIpServer();
}
} /// <summary>
/// 检测IP服务器是否连接
/// </summary>
private void DataRevIP()
{
if (socketIP.Poll(-1, SelectMode.SelectRead))
{
byte[] m=new byte[1024];
int nRead = socketIP.Receive(m);
if (nRead == 0)
{
//socket连接已断开
socketIP.Close();
EvenDisIpServer();
threadIP.Abort();
//ConnIpServer();
}
}
} #endregion
/// <summary>
/// 监视listener等待连接,监视串口猫是否拨号成功与断开拨号
/// </summary>
private void BeginListen()
{
IPAddress ServerIp=GetServerIP();
IPEndPoint iep=new IPEndPoint(ServerIp,5003);
listener=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//this.label1.Text=iep.ToString();
listener.Bind(iep);
// do
while(true)
{
try
{
//监视串口连接到猫事件
if(_CommConnEn)
{
if(axMSComm.CTSHolding && axMSComm.CDHolding)
{
_CommConnEn=false;
_CommDisConnEn=true;
NetConn("a");//拨号连接成功
}
} //监视串口连接到猫事件
if(_CommDisConnEn)
{
if(!(axMSComm.CTSHolding && axMSComm.CDHolding))
{
_CommDisConnEn=false;
NetDisConn("a");//拨号连接断开
}
} if(_netListen)//是否监听
{
listener.Listen(0);
newSocket=listener.Accept();
newthread = new Thread(new ThreadStart(DataRev)); //创建线程
newthread.IsBackground=true;//设置线程为后台运行
newthread.Start();
_netListen=false;//连接成功后,不允许再进行连接
}
}
catch(SocketException ex)
{
//this.label1.Text+=ex.ToString(); newthread.Abort();
newSocket.Close();
_GprsEn=false;//GPRS连接为假
_netListen=true;
NetDisConn("c");
}
} // while(byteMessage!=null);
}//BeginListen
/// <summary>
/// 发送数据
/// </summary>
/// <param name="sd">发送的数据byte[]</param>
/// <param name="stype">选择发送的连接类型,a猫拨号,b是socket向外连接,c是GPRS连接(先拨号)</param>
public void SendData(byte[] sd,string stype)
{
Form_Main.GetData="";
Form_Main.GetDataLen=0;
Form_Main.GetedLen=0;
Form_Main.DataRev=true;
Form_Main.SendIni(true);
if(stype=="a")//串口操作
{
axMSComm.Output=sd;
}
else
{
if(stype=="b")//网络操作
{
try
{
socketA.Send(sd);
}
catch
{
socketA.Close();
NetDisConn("b");
}
}
else//GPRS操作
{
try
{
newSocket.Send(sd);
}
catch
{
newthread.Abort();
newSocket.Close();
_netListen=true;
_GprsEn=false;//GPRS连接为假
NetDisConn("c");
}
}
}
//++++++++++++++测试++++++++++++
//Form_Main.SendCmdEN=true;
//++++++++++++++++++++++++++++++ } #endregion #region 从comsetup.xml读取串口号
private short XmlGetCommPort()
{
try
{
XmlDocument xmldoc = new XmlDocument();
XmlTextReader reader=new XmlTextReader("comsetup.xml");
xmldoc.Load(reader);
XmlElement NodeEle=xmldoc.DocumentElement;
XmlNodeList NodeList=NodeEle.ChildNodes;
XmlNode Node=NodeList[0];
//MessageBox.Show(Node.InnerText);
return Convert.ToInt16(Node.InnerText);
}
catch
{
return 1;
}
}
#endregion
}
}
因该采用异步方式!