ClassTCPP.cs
上传用户:zhangkuixh
上传日期:2013-09-30
资源大小:5473k
文件大小:14k
源码类别:

搜索引擎

开发平台:

C#

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Collections;
  7. using System.IO;
  8. /*
  9.       '       迅龙中文分类搜索引擎  v0.6
  10.       '
  11.       '        LGPL  许可发行
  12.       '
  13.       '       宁夏大学  张冬 康彩  zd4004@163.com
  14.       ' 
  15.       '        官网 http://blog.163.com/zd4004/
  16.  */
  17. namespace XunLong.NewXWord
  18. {
  19.     /// <summary>
  20.     /// 存储结构
  21.     /// </summary>
  22.     struct DSU
  23.     {
  24.         /// <summary>
  25.         /// 是否忙
  26.         /// </summary>
  27.         public bool isBuse;
  28.         /// <summary>
  29.         /// 需要分的词
  30.         /// </summary>
  31.         public string OldWord;
  32.         /// <summary>
  33.         /// 分词结果
  34.         /// </summary>
  35.         public string Xword;
  36.         /// <summary>
  37.         ///  空闲时间最长的
  38.         /// </summary>
  39.         public int SendZTime;
  40.     
  41.     }
  42.     /// <summary>
  43.     /// 获取和压入文件头数据
  44.     /// </summary>
  45.     class ClassTcpClient
  46.     {
  47.         private Socket clientSocket;
  48.         private const int dataSize = 1024*2;
  49.         private byte[] data = new byte[dataSize];
  50.         
  51.         /// <summary>
  52.         /// 记录TCP状态  key = socket  val = T/F 是否空闲  
  53.         /// </summary>
  54.         public   Hashtable x = new Hashtable();
  55.         /// <summary>
  56.         /// 分词缓存  key =old  val = jguo
  57.         /// </summary>
  58.         Hashtable Y = new Hashtable();
  59.         /// <summary>
  60.         /// 存放得到的数据
  61.         /// </summary>
  62.         private  string GetOneData = "";
  63.         /// <summary>
  64.         /// 编码 
  65.         /// </summary>
  66.         NewNxuEncoding.CNewNxuEncoding mCode = new NewNxuEncoding.CNewNxuEncoding();
  67.         //文件
  68.         StreamWriter w_writer = null;
  69.         /// <summary>
  70.         /// 得到1个值
  71.         /// </summary>
  72.         /// <param name="dat"></param>
  73.         /// <returns></returns>
  74.         public string GetOneEnd(string dat)
  75.         {
  76.             if (Y.Contains(dat) == true)
  77.             {
  78.                 return Y[dat].ToString();
  79.             }
  80.             return null;
  81.         }
  82.      
  83.         public bool Conn(string ip, int port)
  84.         {
  85.             IPAddress myIP;
  86.             IPEndPoint iep;
  87.             try
  88.             {
  89.                 myIP = IPAddress.Parse(ip);
  90.                 iep = new IPEndPoint(myIP, port);
  91.             }
  92.             catch
  93.             {
  94.                 Console.WriteLine("你输入的服务器名或端口号格式不正确,请重新输入!");
  95.                 return false;
  96.             }
  97.             Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  98.             socket.SendTimeout = 500;
  99.             socket.ReceiveTimeout = 500;
  100.             socket.BeginConnect(iep, new AsyncCallback(ConnectServer), socket);
  101.             return true;
  102.         }
  103.         private void ConnectServer(IAsyncResult ar)
  104.         {
  105.             Socket clientSocket0 = (Socket)ar.AsyncState;
  106.             try
  107.             {
  108.                 clientSocket0.EndConnect(ar);
  109.                 // Console.WriteLine("与服务器" + clientSocket.RemoteEndPoint.ToString() + "连接成功。");
  110.                 clientSocket0.BeginReceive(data, 0, dataSize, SocketFlags.None, new AsyncCallback(ReceiveData), clientSocket0);
  111.                 if (x.Contains(clientSocket0) == false)
  112.                 {
  113.                     DSU a = new DSU();
  114.                     a.isBuse = false;
  115.                     a.OldWord = "";
  116.                     a.Xword = "";
  117.                     a.SendZTime = Environment.TickCount;
  118.                     x.Add(clientSocket0, a);
  119.                 }
  120.                 else
  121.                 {
  122.                     DSU a = new DSU();
  123.                     a.isBuse = false;
  124.                     a.OldWord = "";
  125.                     a.Xword = "";
  126.                     a.SendZTime = Environment.TickCount;
  127.                     x[clientSocket0] = a;
  128.                 }
  129.                 Console.WriteLine("-连接成功-> " + clientSocket0.RemoteEndPoint.ToString()   );
  130.             }
  131.             catch
  132.             {
  133.                 // Console.WriteLine("与服务器连接失败!");
  134.                 if (x.Contains(clientSocket0) == true)
  135.                 {
  136.                     x.Remove(clientSocket0);
  137.                 }
  138.             }
  139.         }
  140.         private void ReceiveData(IAsyncResult ar)
  141.         {
  142.              Socket server = (Socket)ar.AsyncState;
  143.             try
  144.             {
  145.                 int receiveDataLength = server.EndReceive(ar);
  146.               //  string str = System.Text.Encoding.Unicode.GetString(data, 0, receiveDataLength);
  147.                 Encoding gbx = System.Text.Encoding.GetEncoding("gb2312");
  148.                 string str =gbx.GetString(data, 0, receiveDataLength-1);
  149.                 DSU a = (DSU)x[server];
  150.                 try
  151.                 {
  152.                     //GetOneData = str;
  153.                     if (Y.Contains(a.OldWord) == true)
  154.                     {
  155.                     }
  156.                     else
  157.                     {
  158.                         Y.Add(a.OldWord, str);
  159.                     }
  160.                 }
  161.                 catch
  162.                 { 
  163.                 
  164.                 
  165.                 }
  166.                 a.isBuse = false;
  167.                 a.OldWord = "";
  168.                 a.Xword = "";
  169.                 a.SendZTime = Environment.TickCount;
  170.                 //把得到的数据压入分词缓存              
  171.                 x[server] = a;
  172.             }
  173.             catch
  174.             {
  175.                 x.Remove(server);
  176.             }
  177.         }
  178.         public bool SendOneData(string dataIt)
  179.         {
  180.             //找到1个空闲的连接    Environment.TickCount;   空闲时间最长的
  181.             Hashtable x2 = (Hashtable)x.Clone();
  182.             Socket O1 =null;
  183.             int TmpTime = Environment.TickCount+1;
  184.             foreach (System.Collections.DictionaryEntry de in x2)
  185.             {
  186.                 DSU a = (DSU)de.Value;
  187.                 if (a.isBuse ==true )
  188.                 { }
  189.                 else
  190.                 {
  191.                     if (a.SendZTime < TmpTime)
  192.                     {
  193.                         TmpTime = a.SendZTime;
  194.                         try
  195.                         {
  196.                             O1 = (Socket)de.Key;
  197.                         }
  198.                         catch
  199.                         {  }
  200.                     }
  201.                 }
  202.             }
  203.             if (O1 == null)
  204.             {
  205.                 //清理掉超时的任务
  206.                 foreach (System.Collections.DictionaryEntry de in x2)
  207.                 {
  208.                     DSU a = (DSU)de.Value;
  209.                     if (a.isBuse == true)
  210.                     {
  211.                         if (a.SendZTime+1600 < Environment.TickCount)
  212.                         {                         
  213.                             try
  214.                             {
  215.                                 Socket pp = (Socket)de.Key;
  216.                                 pp.Close();
  217.                                 x.Remove(de.Key);
  218.                             }
  219.                             catch
  220.                             { }
  221.                         }
  222.                     }
  223.                 }
  224.                 Console.WriteLine("-缺乏有效可用分词服务-〉");
  225.                 return false;
  226.             }
  227.             else
  228.             {
  229.                 Encoding gbx = System.Text.Encoding.GetEncoding("gb2312");
  230.                 byte[] message = gbx.GetBytes(dataIt);
  231.                 O1.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(SendData), O1);
  232.                 DSU a = new DSU();
  233.                 a.OldWord = dataIt;
  234.                 a.isBuse = true;
  235.                 a.Xword = "";
  236.                 a.SendZTime = Environment.TickCount;
  237.                 x[O1] = a;
  238.                 //清理掉超时的任务
  239.                 foreach (System.Collections.DictionaryEntry de in x2)
  240.                 {
  241.                     DSU avv = (DSU)de.Value;
  242.                     if (avv.isBuse == true)
  243.                     {
  244.                         if (avv.SendZTime + 1600 < Environment.TickCount)
  245.                         {
  246.                             try
  247.                             {
  248.                                 Socket pp = (Socket)de.Key;
  249.                                 pp.Close();
  250.                                 x.Remove(de.Key);
  251.                             }
  252.                             catch
  253.                             { }
  254.                         }
  255.                     }
  256.                 }
  257.                 return true;
  258.             }
  259.            
  260.         }
  261.         private void SendData(IAsyncResult ar)
  262.         {
  263.             Socket socketE = (Socket)ar.AsyncState;
  264.             try
  265.             {
  266.                 int send = socketE.EndSend(ar);
  267.                 socketE.BeginReceive(data, 0, dataSize, SocketFlags.None, new AsyncCallback(ReceiveData), socketE);
  268.             }
  269.             catch
  270.             {
  271.                 x.Remove(socketE);
  272.             }
  273.         }
  274.         /// <summary>
  275.         /// 关闭连接
  276.         /// </summary>
  277.         public void ConnStop()
  278.         {
  279.          
  280.         }
  281.         /// <summary>
  282.         /// 初始化已经分词的结果 可以用来加速
  283.         /// </summary>
  284.         /// <param name="okPath">使用缓存服务器的缓存数据</param>
  285.         public void initOKxWord(string okPath)
  286.         {
  287.             //初始化分词缓存
  288.             Y.Clear();
  289.             StreamReader reader = null;
  290.             try
  291.             {
  292.                 reader = new StreamReader(okPath, System.Text.Encoding.GetEncoding("gb2312"));
  293.                 for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
  294.                 {
  295.                     if (line != null)
  296.                     {
  297.                         if (line.IndexOf('t') > 0)
  298.                         {
  299.                             string[] mxd = line.Split('t');
  300.                             //解码
  301.                             mxd[0] = mCode.CODE2CN(mxd[0]);
  302.                             mxd[1] = mCode.CODE2CN(mxd[1]);
  303.                             if (Y.Contains(mxd[0]) == false)
  304.                             {
  305.                                 Y.Add(mxd[0], mxd[1]);
  306.                             }
  307.                         }
  308.                     }
  309.                 }
  310.                 reader.Close();
  311.             }
  312.             catch (IOException e)
  313.             {
  314.                 Console.WriteLine(e.Message);
  315.             }
  316.             finally
  317.             {
  318.                 if (reader != null)
  319.                     reader.Close();
  320.             }
  321.             Console.WriteLine("-共加载分词缓存数据-> "+Y.Count.ToString()+" 条");
  322.         }
  323.         /// <summary>
  324.         /// 写入一条数据
  325.         /// </summary>
  326.         /// <param name="filename">文件名</param>
  327.         /// <param name="data">数据</param>
  328.         /// <param name="isApp">是否追加模式</param>
  329.         public void putXwordCacheFileData_A(string okPath, string data)
  330.         {
  331.             StreamWriter writer = null;
  332.             try
  333.             {
  334.                 writer = new StreamWriter(okPath, true, System.Text.Encoding.GetEncoding("gb2312"));
  335.                 //  writer.Write(data);
  336.                 writer.WriteLine(data);
  337.                 writer.Close();
  338.             }
  339.             catch (IOException e)
  340.             {
  341.                 Console.WriteLine(e.Message);
  342.             }
  343.             finally
  344.             {
  345.                 if (writer != null)
  346.                     writer.Close();
  347.             }
  348.             Console.WriteLine("=-当前共有分词缓存数据-> " + Y.Count.ToString() + " 条");
  349.         }
  350.         /// <summary>
  351.         /// 写入一条数据
  352.         /// </summary>
  353.         /// <param name="filename">文件名</param>
  354.         /// <param name="data">数据</param>
  355.         /// <param name="isApp">是否追加模式</param>
  356.         public void putXwordCacheFileData_Write(string okPath, string data)
  357.         {
  358.           
  359.             try
  360.             {      
  361.                 w_writer.WriteLine(data);
  362.               
  363.             }
  364.             catch (IOException e)
  365.             {
  366.                 Console.WriteLine(e.Message);
  367.                 Console.WriteLine("严重错误!!!");
  368.                 System.Threading.Thread.Sleep(1000);
  369.             }
  370.           
  371.             Console.WriteLine("写入数据=-当前共有分词缓存数据-> " + Y.Count.ToString() + " 条");
  372.         }
  373.         /// <summary>
  374.         /// 打开文件
  375.         /// </summary>
  376.         /// <param name="filename">文件名</param>
  377.         /// <param name="data">数据</param>
  378.         /// <param name="isApp">是否追加模式</param>
  379.         public void putXwordCacheFileData_Open(string okPath, string data)
  380.         {
  381.           
  382.             try
  383.             {
  384.                 w_writer = new StreamWriter(okPath, true, System.Text.Encoding.GetEncoding("gb2312"));
  385.               
  386.             }
  387.             catch (IOException e)
  388.             {
  389.                 Console.WriteLine(e.Message);
  390.                 Console.WriteLine("严重错误!!!");
  391.                 System.Threading.Thread.Sleep(1000000);
  392.             }
  393.             Console.WriteLine("打开数据=-当前共有分词缓存数据-> " + Y.Count.ToString() + " 条");
  394.         }
  395.         /// <summary>
  396.         /// 关闭
  397.         /// </summary>
  398.         /// <param name="filename">文件名</param>
  399.         /// <param name="data">数据</param>
  400.         /// <param name="isApp">是否追加模式</param>
  401.         public void putXwordCacheFileData_Close(string okPath, string data)
  402.         {
  403.          
  404.             try
  405.             {
  406.                 w_writer.Close();
  407.             }
  408.             catch (IOException e)
  409.             {
  410.                 Console.WriteLine(e.Message);
  411.             }
  412.             finally
  413.             {
  414.                 if (w_writer != null)
  415.                     w_writer.Close();
  416.             }
  417.             Console.WriteLine("关闭数据=-当前共有分词缓存数据-> " + Y.Count.ToString() + " 条");
  418.         }
  419.     }
  420. }