A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© sunrise2 高级黑马   /  2014-7-21 21:31  /  2301 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

             在做网络通讯方面的程序时,必不可少的是Socket通讯。
        那么我们需要有一套既定的,简易的通讯流程。
如下:
  1. <pre name="code" class="csharp">public class PublicSocket
  2.     {
  3.         public const string DOWNLOAD_STATUS_WAIT = "1";
  4.         public const string DOWNLOAD_STATUS_PAUSE = "2";
  5.         public const string DOWNLOAD_STATUS_DOWNLOADING = "3";
  6.         public const string DOWNLOAD_STATUS_DOWNLOADED = "4";
  7.         public const string DOWNLOAD_STATUS_ERROR = "5";

  8.         //private XmlHelper xmlhelper = new XmlHelper();
  9.         private TcpClient tcpMethod = new TcpClient();
  10.         public static string LoginUserName = "";
  11.         public static Socket HeadClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  12.         private static string iAddress = "192.168.1.1";
  13.         private static int iPort = 7888;
  14.         private static IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(iAddress), iPort);

  15.         public const int LOGIN_NAMEERROR = 100000;
  16.         public const int LOGIN_CODEERROR = 100001;
  17.         public const int LOGIN_ERROR = 100002;
  18.         public const int LOGIN_OK = 100003;
  19.         public static bool AllowUpdate = true;

  20.         public static void SocketConnect()
  21.         {
  22.             try
  23.             {
  24.                 if (!HeadClient.Connected)
  25.                 {
  26.                     HeadClient.Connect(endpoint);
  27.                 }
  28.             }
  29.             catch (Exception ex)
  30.             { }
  31.         }

  32.         public static void SocketClose()
  33.         {
  34.             if (HeadClient.Connected)
  35.             {
  36.                 HeadClient.Close();
  37.             }
  38.         }
  39. public static void ThreadGetSingleDownloadedFile(object data)   //object参数可以实现界面传入数据进行使用
  40.         {
  41.             string retMD5 = string.Empty;
  42.             try
  43.             {
  44.                 HanleListItemClass formInter = data as HanleListItemClass;

  45.                 XmlDocument aa = XmlHelper.BuildXmlDoc("CMD", "1", "1",
  46.                  new List<HollXmlNode> { new HollXmlNode("ID","2",null),
  47.                                         new HollXmlNode("STATE","127",null) });
  48.                 //主要为了构建XML文件进行Socket的send操作
  49.                 //构造后如下  <?xml version='1.0' encoding='utf-8'?><CMD code='1'  index='1'>
  50.                 //                 <ID>2</ID>
  51.                  //                <STATE>127</STATE></CMD>

  52.                 byte[] sendaskbyte = Encoding.UTF8.GetBytes(aa.InnerXml.ToString());
  53.                 int sendcount = 0;

  54.                 try
  55.                 {
  56.                     sendcount = HeadClient.Send(sendaskbyte, sendaskbyte.Length, 0);
  57.                 }
  58.                 catch (Exception ex)
  59.                 {
  60.                     // return LOGIN_ERROR;
  61.                 }


  62.                 if (sendcount == 0)
  63.                 {
  64.                     //return LOGIN_ERROR;
  65.                 }

  66.                 int ret = SingleDownloadedFileWaitBack(formInter);

  67.             }
  68.             catch
  69.             {
  70.                 //return LOGIN_ERROR;
  71.             }
  72.         }

  73.         public static int SingleDownloadedFileWaitBack(HanleListItemClass tItemclass)
  74.         {
  75.             byte[] RetData = new byte[36 * 1024];
  76.             Array.Clear(RetData, 0, RetData.Length);
  77.             int datalen = 0;

  78.             try
  79.             {
  80.                 datalen = HeadClient.Receive(RetData);

  81.                 if (datalen == 0)
  82.                 {
  83.                     return -1;
  84.                 }

  85.                 //接收到服务器返回的信息
  86.                 string tcpdatastring = Encoding.UTF8.GetString(RetData).Replace("\0", " "); ;

  87.                 //此处可以根据自己需求处理返回的信息 http://www.cnblogs.com/sosoft/
  88.                 return 0;

  89.             }
  90.             catch (Exception ex)
  91.             {
  92.                 return 0;
  93.             }
  94.         }
  95.     }
复制代码

然后再界面调用的时候,我们只需要在事件中这么使用即可
  1. private void button1_Click(object sender, EventArgs e)   

  2.     {  PublicSocket.SocketConnect();   

  3.             ThreadPool.QueueUserWorkItem(new WaitCallback(SocketMethod.ThreadGetTotalState), this);     

  4.   }
复制代码

同时也把构建XML的类分享出来,使得编码更加简便
  1. public class XmlHelper
  2.     {
  3.         private static string xmlinit = "<?xml version='1.0' encoding='utf-8'?><{0} code='{1}'  index='{2}'></{0}>";

  4.         public static XmlDocument BuildXmlDoc(string xmltype, string code, string index, List<HollXmlNode> xmlnodes)
  5.         {
  6.             XmlDocument root = new XmlDocument();
  7.             root.LoadXml(string.Format(xmlinit, xmltype, code, index));

  8.             if (xmlnodes != null)
  9.             {
  10.                 for (int i = 0; i < xmlnodes.Count; i++)
  11.                 {
  12.                     XmlElement parentNode = root.CreateElement(xmlnodes[i].NodeName);

  13.                     XmlText descText = root.CreateTextNode(xmlnodes[i].NodeValue);
  14.                     parentNode.AppendChild(descText);


  15.                     if (xmlnodes[i].NodeAtt != null)
  16.                     {
  17.                         if (xmlnodes[i].NodeAtt.Count > 0)
  18.                         {
  19.                             for (int j = 0; j < xmlnodes[i].NodeAtt.Count; j++)
  20.                             {
  21.                                 parentNode.SetAttribute(xmlnodes[i].NodeAtt[j].AttName, xmlnodes[i].NodeAtt[j].AttValue);
  22.                             }
  23.                         }
  24.                     }

  25.                     root.LastChild.AppendChild(parentNode);
  26.                 }
  27.             }

  28.             return root;
  29.         }

  30.     }
复制代码
  1. public class HollXmlNode
  2.     {
  3.         private string _nodename;
  4.         private string _nodevalue;
  5.         private List<HollXmlAttribute> _nodeatt;


  6.         public HollXmlNode(string tnodename, string tnodevalue, List<HollXmlAttribute> tnodeatt)
  7.         {
  8.             _nodename = tnodename;
  9.             _nodevalue = tnodevalue;
  10.             _nodeatt = tnodeatt;
  11.         }


  12.         public string NodeName
  13.         {
  14.             get { return _nodename; }
  15.             set { _nodename = value; }
  16.         }

  17.         public string NodeValue
  18.         {
  19.             get { return _nodevalue; }
  20.             set { _nodevalue = value; }
  21.         }

  22.         public List<HollXmlAttribute> NodeAtt
  23.         {
  24.             get { return _nodeatt; }
  25.             set { _nodeatt = value; }
  26.         }
  27.     }

  28.     public class HollXmlAttribute
  29.     {
  30.         private string _attname;
  31.         private string _attvalue;

  32.         public HollXmlAttribute(string tname, string tvalue)
  33.         {
  34.             _attname = tname;
  35.             _attvalue = tvalue;
  36.         }

  37.         public string AttName
  38.         {
  39.             get { return _attname; }
  40.             set { _attname = value; }
  41.         }

  42.         public string AttValue
  43.         {
  44.             get { return _attvalue; }
  45.             set { _attvalue = value; }
  46.         }
  47.     }
复制代码


3 个回复

倒序浏览
似成相识。
回复 使用道具 举报
看起来晕晕的感觉
回复 使用道具 举报
谢谢分享 看晕了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马