⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 gatewayservice.cs

📁 用于移动梦网网关进行TCP通信,可以收发短信,并实现计费功能.使用SOCKET实现,并具有收发读写保护功能.可作为TCP通信和线程读写同步的教程.
💻 CS
📖 第 1 页 / 共 2 页
字号:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using System.Text;
using System.Windows;
using System.Data.SqlClient;
using System.IO;
using System.Xml;
using System.Net;

namespace GateWayFroCMPP3
{
	public class CMPP3GateWayService : System.ServiceProcess.ServiceBase
	{
		private CMPP3.Client.CMPP3Client cmppClient;//=new CMPP.client.CMPPClient();
		/// <summary>
		/// 网关所在IP
		/// </summary>
		private string CM_GateWayIP;//真实网关IP
		/// <summary>
		/// 网关端口
		/// </summary>
		private int CM_GateWayPort;//真实网关端口
		/// <summary>
		/// 网关分配企业代码
		/// </summary>
		private string SPID;
		/// <summary>
		/// 网关分配服务号码
		/// </summary>
		private string ServiceCode;//特服号
		/// <summary>
		/// 登陆用户名
		/// </summary>
		private string SendUserName;
		/// <summary>
		/// 登陆密码
		/// </summary>
		private string SendPassWord;
		/**************************主服务程序配置*********************************/
		private string GateWayID;
		private string GateWayPWD;
		private string IsmgServerName;
		private int IsmgServerPort;
		
		private System.Threading.AutoResetEvent ARE_ISMGConnect=new AutoResetEvent(false);
		/***************************数据库连接配置*****************************/
		private string DataBaseConnectString;
		private System.Data.SqlClient.SqlConnection SqlConn;
		private System.Data.SqlClient.SqlCommand SqlComm;
		/***************************平台标志位及其他配置***********************/
		private bool isStart=false;
		private bool HandStop=false;
		private byte[] LastData=new byte[0];
		private ReaderWriterLock RWL_MSMQ_Temp=new ReaderWriterLock();
		private System.Threading.AutoResetEvent ARE_Start=new AutoResetEvent(false);
		private System.Threading.Thread ThreadStart;
		/// <summary>
		/// 运营商编号
		/// </summary>
		private int TelOperatorID;
		/// <summary>
		/// 整型的网关号
		/// </summary>
		private int iGatewayID;
		
		private string path;
		private ReaderWriterLock RWL_log=new ReaderWriterLock();
		private System.Messaging.MessageQueue RecvSMBPQueue;
		private System.Messaging.MessageQueue SendSMBPQueue;
		private System.Threading.ReaderWriterLock RWL_SendSmbppQueue=new ReaderWriterLock();
		//private ReaderWriterLock RWL_SendQueue=new ReaderWriterLock();
		/// <summary>
		/// 受系统是否启动所控制
		/// </summary>
		private bool IfCanSendMsg=false;
		private ReaderWriterLock RWL_IfCanSendMsg=new ReaderWriterLock();
		private System.Messaging.MessageQueue MSMQ_TempQueue;
		private int ResendTimes=3;
		/// <summary> 
		/// 必需的设计器变量。
		/// </summary>
		private System.ComponentModel.Container components = null;

		public CMPP3GateWayService()
		{
			// 该调用是 Windows.Forms 组件设计器所必需的。
			InitializeComponent();

			// TODO: 在 InitComponent 调用后添加任何初始化
		}

		// 进程的主入口点
		static void Main()
		{
			System.ServiceProcess.ServiceBase[] ServicesToRun;
	
			// 同一进程中可以运行多个用户服务。若要将
			//另一个服务添加到此进程,请更改下行
			// 以创建另一个服务对象。例如,
			//
			//   ServicesToRun = New System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
			//
			ServicesToRun = new System.ServiceProcess.ServiceBase[] { new CMPP3GateWayService() };

			System.ServiceProcess.ServiceBase.Run(ServicesToRun);
		}

		/// <summary> 
		/// 设计器支持所需的方法 - 不要使用代码编辑器 
		/// 修改此方法的内容。
		/// </summary>
		private void InitializeComponent()
		{
			// 
			// CMPP3GateWayService
			// 
			this.ServiceName = "CMPP3GateWayService";

		}

		/// <summary>
		/// 清理所有正在使用的资源。
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		/// <summary>
		/// 设置具体的操作,以便服务可以执行它的工作。
		/// </summary>
		protected override void OnStart(string[] args)
		{
			// TODO: 在此处添加代码以启动服务。
			//Thread.Sleep(20000);
			string queuepath=@".\Private$\SmbppSrvCmppGateWayTempQueue";
			if(!System.Messaging.MessageQueue.Exists(queuepath))
			{
				//System.Messaging.MessageQueue.Delete(".\\Private$\\GateWayLogQueue");
				System.Messaging.MessageQueue.Create(queuepath);
			}
			
			if(this.MSMQ_TempQueue!=null)
			{
				this.MSMQ_TempQueue.Close();
				this.MSMQ_TempQueue.Dispose();
			}
			else
			{
				this.MSMQ_TempQueue=new System.Messaging.MessageQueue(queuepath);
				this.MSMQ_TempQueue.Formatter=new System.Messaging.BinaryMessageFormatter(System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full, System.Runtime.Serialization.Formatters.FormatterTypeStyle.TypesAlways);
				this.MSMQ_TempQueue.ReceiveCompleted+=new System.Messaging.ReceiveCompletedEventHandler(MSMQ_TempQueue_ReceiveCompleted);
		
			}
			
			
			
			this.path=System.Windows.Forms.Application.StartupPath;
			this.MSMQ_TempQueue.BeginReceive();
			//this.RWL_log.ReleaseLock();
			this.TobeStart();	
		}
		//准备启动
		private void TobeStart()
		{
			this.HandStop=false;
			this.ThreadStart=new Thread(new ThreadStart(this.ServiceStart));
			this.ThreadStart.Start();
		}
		/// <summary>
		/// 启动线程避免管理器无法控制
		/// </summary>
		private void ServiceStart()
		{
			while(!this.HandStop)
			{
				this.ARE_Start.Reset();
				this.OneStart();
				this.ARE_Start.WaitOne();
				//启动失败,系统冷却60S
				Thread.Sleep(60000);
			}
		}
		/// <summary>
		/// 进行一次启动
		/// </summary>
		private void OneStart()
		{
			this.isStart=true;
			string log;
			bool initcon=this.InitConfig();
			if(!initcon)
			{
				//配置信息读取失败
				log="配置信息读取失败";
				this.WriteLogFile(log);
				this.ARE_Start.Set();
				return;
			}
			log="配置信息读取成功";
			this.WriteLogFile(log);
			#region <建立收发队列>
			string RecvPath=@".\Private$\smbppSrvService_SMBPPToGateWay_"+this.GateWayID+"_queue";
			if(!System.Messaging.MessageQueue.Exists(RecvPath))
			{
				System.Messaging.MessageQueue.Create(RecvPath);
			}
			this.RecvSMBPQueue=new System.Messaging.MessageQueue(RecvPath,false);
			RecvSMBPQueue.Formatter=new System.Messaging.BinaryMessageFormatter(System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full, System.Runtime.Serialization.Formatters.FormatterTypeStyle.TypesAlways);
			RecvSMBPQueue.ReceiveCompleted+=new System.Messaging.ReceiveCompletedEventHandler(RecvSMBPQueue_ReceiveCompleted);
			string SendPath=@".\Private$\smbppSrvService_GateWayToSMBP_"+this.GateWayID+"_queue";
			if(!System.Messaging.MessageQueue.Exists(SendPath))
			{
				System.Messaging.MessageQueue.Create(SendPath);
			}
			this.SendSMBPQueue=new System.Messaging.MessageQueue(SendPath,false);
			SendSMBPQueue.Formatter=new System.Messaging.BinaryMessageFormatter(System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full, System.Runtime.Serialization.Formatters.FormatterTypeStyle.TypesAlways);
			#endregion
			IPAddress GateWayIPAddress=IPAddress.Parse(this.CM_GateWayIP);
			this.cmppClient=new CMPP3.Client.CMPP3Client(this.SPID,this.SendUserName,this.SendPassWord,GateWayIPAddress,this.CM_GateWayPort,this.ServiceCode);
			this.cmppClient.onRequestRestartHandler+=new CMPP3.Client.RequestRestartEventHandler(cmppClient_onRequestRestartHandler);
			this.cmppClient.onSentTestHandler+=new CMPP3.Client.SentTestEventHandler(cmppClient_onSentTestHandler);
			this.cmppClient.onReceiveTestRespHandler+=new CMPP3.Client.RecvTestRespEventHandler(cmppClient_onReceiveTestRespHandler);
			this.cmppClient.onErrorHandler+=new CMPP3.Client.ErrorEventHandler(cmppClient_onErrorHandler);
			this.cmppClient.onFailedItemDeletedHandler+=new CMPP3.Client.FailedItemDeletedEventHandler(cmppClient_onFailedItemDeletedHandler);
			this.cmppClient.onLoginSuccessHandler+=new CMPP3.Client.LoginSuccEventHandler(cmppClient_onLoginSuccessHandler);
			this.cmppClient.onReceiveCancelRespHandler+=new CMPP3.Client.RecvCancelRespEventHandler(cmppClient_onReceiveCancelRespHandler);
			this.cmppClient.onReceiveConnectRespHandler+=new CMPP3.Client.RecvConnectRespEventHandler(cmppClient_onReceiveConnectRespHandler);
			this.cmppClient.onReceiveNewShortMessageHandler+=new CMPP3.Client.RecvSMSEnventHandler(cmppClient_onReceiveNewShortMessageHandler);
			this.cmppClient.onReceiveQueryRespHandler+=new CMPP3.Client.RecvQueryRespEventHandler(cmppClient_onReceiveQueryRespHandler);
			this.cmppClient.onReceiveReportHandler+=new CMPP3.Client.RecvReportEventHandler(cmppClient_onReceiveReportHandler);
			this.cmppClient.onReceiveSubmitRespHandler+=new CMPP3.Client.RecvSubmitRespEventHandler(cmppClient_onReceiveSubmitRespHandler);
			this.cmppClient.onReceiveTerminateRespHandler+=new CMPP3.Client.RecvTerminateRespEventHandler(cmppClient_onReceiveTerminateRespHandler);
			this.cmppClient.onSentTerminateHander+=new CMPP3.Client.SentTerminateEventHandler(cmppClient_onSentTerminateHander);
			int state=this.cmppClient.Start();
			if(state!=0)
			{
				string _log="连接或登陆网关失败,错误代码"+state.ToString();
				this.WriteLogFile(_log);
				this.cmppClient.Dispose();
				this.RecvSMBPQueue.Close();
				this.RecvSMBPQueue.Dispose();
				this.SendSMBPQueue.Close();
				this.SendSMBPQueue.Dispose();
				this.ARE_Start.Set();
				return;
			}
			else
			{
				string _log="登陆网关成功!";
				this.WriteLogFile(_log);
			}
			this.SetIfCanSendMsg(true);
			this.RecvSMBPQueue.BeginReceive();
		}
		private void SetIfCanSendMsg(bool b)
		{
			this.RWL_IfCanSendMsg.AcquireWriterLock(-1);
			this.IfCanSendMsg=b;
			this.RWL_IfCanSendMsg.ReleaseWriterLock();
			Thread.Sleep(1);
		}
		private bool InitConfig()
		{
			//bool b=true;
			string log="开始读取配置信息";
			lock(this)
			{
				this.WriteLogFile(log);
				//this.richTextBox1.Text+=DateTime.Now.ToLongTimeString()+"    "+log+"\r\n";
			}
			ReadConfig  rc=new ReadConfig(this.path+"\\config.xml");
			this.GateWayID=rc.GetValueByName("GateWay","GateWayID");
			this.GateWayPWD=rc.GetValueByName("GateWay","GateWayPWD");
			this.IsmgServerName=rc.GetValueByName("GateWay","IsmgServerName");
			string _IsmgServerPort=rc.GetValueByName("GateWay","IsmgServerPort");
			
			if(this.GateWayID==null||this.GateWayPWD==null||this.IsmgServerName==null)
			{
				log="读取配置失败";
				lock(this)
				{
					this.WriteLogFile(log);
					//this.richTextBox1.Text+=DateTime.Now.ToLongTimeString()+"    "+log+"\r\n";
				}
				return false;
			}
			try
			{
				this.IsmgServerPort=int.Parse(_IsmgServerPort);
			}
			catch
			{
				log="读取的IsmgServerPort不合法";
				lock(this)
				{
					this.WriteLogFile(log);
					//this.richTextBox1.Text+=DateTime.Now.ToLongTimeString()+"    "+log+"\r\n";
				}
				return false;
			}
			try
			{
				this.iGatewayID=int.Parse(GateWayID);
			}
			catch
			{
				log="读取的GateWayID不合法";
				lock(this)
				{
					this.WriteLogFile(log);
					//this.richTextBox1.Text+=DateTime.Now.ToLongTimeString()+"    "+log+"\r\n";
				}
				return false;
			}
			string dbip=rc.GetValueByName("DataBase","server");
			string userid=rc.GetValueByName("DataBase","UserID");
			string psw=rc.GetValueByName("DataBase","PassWord");
			this.DataBaseConnectString="server="+dbip+";database=Smbp_JDG;user id="+userid+";password="+psw+";";
			this.SqlConn=new SqlConnection(this.DataBaseConnectString);
			this.SqlComm=new SqlCommand();
			this.SqlComm.Connection=this.SqlConn;
			bool b=true;
			try
			{
				this.SqlConn.Open();
				//
			}
			catch
			{
				
			}
			finally
			{
				
				if(this.SqlConn.State==ConnectionState.Open)
				{
					this.SqlConn.Close();
					string sqltxt="select * from Smbp_Gateway where GateWayID=@gw";
					SqlDataAdapter sda=new SqlDataAdapter(sqltxt,this.SqlConn);
					sda.SelectCommand.Parameters.Add("@gw",this.iGatewayID);
					DataSet ds=new DataSet();
					sda.Fill(ds);
					if(ds.Tables[0].Rows.Count==0)
					{
						log="没有找到此网关的配置";
						lock(this)
						{
							this.WriteLogFile(log);
							//this.richTextBox1.Text+=DateTime.Now.ToLongTimeString()+"    "+log+"\r\n";
						}
						b=false;
					}
					else
					{
						try
						{
							this.SPID=(string)ds.Tables[0].Rows[0]["SPID"];
							this.ServiceCode=(string)ds.Tables[0].Rows[0]["ServiceCode"];
							this.SendUserName=(string)ds.Tables[0].Rows[0]["SendUserName"];
							this.SendPassWord=(string)ds.Tables[0].Rows[0]["SendPassWord"];

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -