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

📄 csock_file.cs

📁 自定义协议
💻 CS
📖 第 1 页 / 共 2 页
字号:
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;

namespace CodeManagerService
{

	/// <summary>
	/// CSock_File 的摘要说明。
	/// </summary>
	public class CSock_File
	{
		private DateTime m_dActive;
		private bool m_Enable;
		private Thread threadproc;
		private static Thread threadactive;
		private TcpClient m_sock;
		private static bool bSwitch;
		private String m_sAccount_Home;
		private String m_sPath;
		private FileStream fs;
		private BinaryReader r;
		private BinaryWriter w;

		private int nfindex;
		private static TcpListener cmsg_server_info;
		private static ArrayList cmsg_array_file = null;


		public CSock_File()
		{
			//
			// TODO: 在此处添加构造函数逻辑
			//
			m_sock = null;
			m_Enable = true;
		}

		/// <summary>
		/// 错误日志
		/// </summary>
		/// <param name="szMsg">记录信息</param>
		private static void logs(string szMsg)
		{
			DateTime dt=DateTime.Now;
			String szFile=string.Format("c:/log/cmsg_log{0}.log", DateTime.Now.ToLongDateString());
			lock(typeof(CSock_File))
			{
				using (StreamWriter sw = new StreamWriter(szFile, true)) 
				{
					sw.WriteLine(string.Format("[{0}]:{1}",DateTime.Now, szMsg));
				}
			}
		}


		/// <summary>
		/// 管理线程启动
		/// </summary>
		public static void start()
		{
			// init var
			cmsg_array_file = new ArrayList();

			// init params
			bSwitch = true;
			Int32 port = 8901;
			IPAddress localAddr = IPAddress.Parse("127.0.0.1");
    
			// TcpListener server = new TcpListener(port);
			cmsg_server_info = new TcpListener(port);

			// Start listening for client requests.
			cmsg_server_info.Start();
			logs("cmsg server file listeing...");
			
			//线路检测
			threadactive = new Thread( new ThreadStart( Active_Test ) ); 
			threadactive.IsBackground = true;
			threadactive.Start();
			//*/

			// Enter the listening loop.
			while(bSwitch) 
			{
				TcpClient client = cmsg_server_info.AcceptTcpClient(); 
				CSock_File cc_sock = new CSock_File();
				cc_sock.m_sock = client;
				cc_sock.threadproc = new Thread( new ThreadStart( cc_sock.DoProc ) );
				cc_sock.threadproc.IsBackground = true;
				cc_sock.threadproc.Start();
				logs("one cc socket connected.");
				cmsg_array_file.Add(cc_sock);
			}
		}

		/// <summary>
		/// 管理线程结束
		/// </summary>
		public static void stop()
		{
			bSwitch = false;
			cmsg_server_info.Stop();
			logs("cmsg server stop!");

		}

		private void close()
		{
			try
			{
				m_Enable = false;
				if (null != fs)
				{
					try{fs.Close();}
					catch{}
					fs = null;
				}
				m_sock.Close();
				threadproc.Abort();
			}
			finally
			{System.GC.Collect();}
		}


		/// <summary>
		/// 线路检测线程
		/// </summary>
		public static void Active_Test() 
		{
			while(true)
			{
				Thread.Sleep(3000);
				try
				{
					if (cmsg_array_file.Count <= 0 )
						continue;

					// Get a stream object for reading and writing
					for(int i = 0 ; i< cmsg_array_file.Count; i ++)
					{

						//NetworkStream stream =((CSock_File)cmsg_array_file[i]). m_sock.GetStream();
						CSock_File cc = (CSock_File)cmsg_array_file[i];
						if (!bSwitch)
						{
							cc.close();
							cc = null;
							cmsg_array_file.RemoveAt(i);
						}


						//logs("test active!");
						TimeSpan diff1 = DateTime.Now.Subtract(cc.m_dActive);

						//活动测试
						if (!cc.m_Enable ||  diff1.Seconds>30)
						{
							logs("socket 关闭");
							cc.close();
							cc = null;
							cmsg_array_file.RemoveAt(i);
							break;
						}

					}
				}
				catch(SocketException e)
				{
					logs("[Active_Test]cmsg cc socket error!"+ e.Message);
				}
			}
		}

		
		/// <summary>
		/// 工作线程
		/// </summary>
		public void DoProc() 
		{
			try
			{
				Int32 i;
				//byte []buf = new byte[12];
				byte []tmp = null;

				//init param
				int nTotal;
				int nCmd;
				int nSeq;
				MemoryStream ms = null;
				NetworkStream stream = null;

				while(m_Enable)
				{
					Thread.Sleep(10);
					// Get a stream object for reading and writing
					try
					{
						stream = m_sock.GetStream();
					}
					catch(InvalidOperationException ioep)
					{
						m_Enable = false;
						logs(String.Format("(FDoProc_sockstream)Source:{0},TargetSite{1},Message{2}", ioep.Source, ioep.TargetSite, ioep.Message));
						ioep=null;break;
					}
					catch(Exception ep)
					{
						logs(String.Format("(FDoProc_sockstream)Source:{0},TargetSite{1},Message{2}", ep.Source, ep.TargetSite, ep.Message));
						ep=null;continue;
					}

					if (ms != null)
					{
						ms.Position = 0;
						ms.Read(tmp, 0, 4);
						nTotal = BitConverter.ToInt32(tmp, 0);
						if (ms.Length == nTotal && ms.Length > 0)
						{
							tmp = new byte[nTotal-4];
							if ((i = ms.Read(tmp, 0, tmp.Length)) == tmp.Length)
							{
								nCmd = BitConverter.ToInt32(tmp, 0);
								nSeq = BitConverter.ToInt32(tmp, 4);

								ParseCC_Cmd(nCmd, nSeq, defcmd.b2b(tmp, 8, tmp.Length-8));
								//ParseCMSG_FileCmd(nCmd, nSeq, defcmd.b2b(tmp, 8, tmp.Length-8));
								ms.Close();
								ms = null;
							}
						}
					}

					if (null == stream)
						continue;

					if (!stream.DataAvailable)
						continue;

					tmp = new byte[4];

					if ((i = stream.Read(tmp, 0, tmp.Length)) == 4)
					{
						m_dActive = DateTime.Now;
						if (null == ms)
							ms = new MemoryStream();
						else
							ms.Position = ms.Length;
						ms.Write(tmp, 0, i);
					}
					stream.Flush();
					tmp = new byte[BitConverter.ToInt32(tmp, 0)-4];
					if ((i = stream.Read(tmp, 0, tmp.Length)) == tmp.Length)
						ms.Write(tmp, 0, tmp.Length);
					else
						ms.Write(tmp, 0, i);
					/*

					tmp = new byte[1024];

					if ((i = stream.Read(tmp, 0, tmp.Length)) > 4)
					{
						m_dActive = DateTime.Now;
						if (null == ms)
							ms = new MemoryStream(8300);
						else
							ms.Position = ms.Length;
						ms.Write(tmp, 0, i);
					}
					stream.Flush();

					if (ms.Length > 4)
					{
						tmp = new byte[4];
						ms.Position = 0;
						if ((i = ms.Read(tmp, 0, 4)) == 4)
						{
							nTotal = BitConverter.ToInt32(tmp, 0);
							if (ms.Length >= (nTotal - 4))
								tmp = new byte[nTotal - 4];
							if ((i = ms.Read(tmp, 0, nTotal - 4))> 0)
							{
								nCmd = BitConverter.ToInt32(tmp, 0);
								nSeq = BitConverter.ToInt32(tmp, 4);

								ParseCC_Cmd(nCmd, nSeq, defcmd.b2b(tmp, 8, tmp.Length-8));
								ms.Close();
								ms = null;
							
							}
						}
					}//*/
				}
				// Shutdown and end connection
				m_sock.Close();
			}
			catch(SocketException e)
			{
				logs("cmsg cc socket_file error!"+ e.Message);
			}
			catch(Exception ep)
			{
				logs(String.Format("(FDoProc)Source:{0},TargetSite{1},Message{2}", ep.Source, ep.TargetSite, ep.Message));
				ep = null;
				
			}
		}

		/// <summary>
		/// 解释包体
		/// </summary>
		/// <param name="cmd">CC命令</param>
		/// <param name="Packet">包体</param>
		private void ParseCC_Cmd(int cmd, int seq, byte[] Packet)
		{
			int nIndex;
			int nLen;
			NetworkStream stream = m_sock.GetStream();
			byte [] bResult = null;
			try
			{
				switch(cmd)
				{
					case defcmd.CONNECT:		//CC登录请求
						/*
						String szPack = "";
						for (int i = 0 ; i < Packet.Length; i ++)
							szPack = String.Format("{0}[{1}]", szPack, Packet[i]);

						logs(szPack);
						//*/

						nIndex = SearchChar(Packet);
						if (nIndex < 0)
						{
							bResult = ResultPacket(defcmd.CONNECT, 3);
							stream.Write(bResult, 0, bResult.Length);
							logs("格式错误!");
							return;
						
						}
						logs(String.Format("nIndex:{0}", nIndex));
						String szAccount = Encoding.GetEncoding(936).GetString(Packet, 0, nIndex);
						logs(szAccount);
						nLen = SearchChar(Packet, nIndex + 1);

						byte bVer = Packet[Packet.Length -11];
						logs(String.Format("version:{0}", bVer));

						//验证版本号
						if (bVer > defcmd.Version)
						{
							bResult = ResultPacket(defcmd.CONNECT, 2);
							stream.Write(bResult, 0, bResult.Length);
							break;
						}
						String szTimestamp = Encoding.Default.GetString(Packet, Packet.Length -10, 10);
						logs(szTimestamp);
						logs(String.Format("nindex[{0}],len[{1}]", nIndex +1, Packet.Length - 13 - nIndex));
						//验证帐号
						if (CheckUser(szAccount, defcmd.b2b(Packet, nIndex +1, Packet.Length - 13 - nIndex), szTimestamp))
						{
							m_Enable = true;
							m_sAccount_Home = szAccount;
							bResult = ResultPacket(defcmd.CONNECT, 0);
							stream.Write(bResult, 0, bResult.Length);
							stream.Flush();
							logs("get file connect ");
						}
						else
						{
							m_Enable = false;
							bResult = ResultPacket(defcmd.CONNECT, 1);

⌨️ 快捷键说明

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