zoukankan      html  css  js  c++  java
  • c# TCP Socket通讯基础

    在做网络通讯方面的程序时,必不可少的是Socket通讯。

    那么我们需要有一套既定的,简易的通讯流程。

    如下:

    <pre name="code" class="csharp">public class PublicSocket
        {
            public const string DOWNLOAD_STATUS_WAIT = "1";
            public const string DOWNLOAD_STATUS_PAUSE = "2";
            public const string DOWNLOAD_STATUS_DOWNLOADING = "3";
            public const string DOWNLOAD_STATUS_DOWNLOADED = "4";
            public const string DOWNLOAD_STATUS_ERROR = "5";
    
    
            //private XmlHelper xmlhelper = new XmlHelper();
            private TcpClient tcpMethod = new TcpClient();
            public static string LoginUserName = "";
            public static Socket HeadClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            private static string iAddress = "192.168.1.1";
            private static int iPort = 7888;
            private static IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(iAddress), iPort);
    
            public const int LOGIN_NAMEERROR = 100000;
            public const int LOGIN_CODEERROR = 100001;
            public const int LOGIN_ERROR = 100002;
            public const int LOGIN_OK = 100003;
    
            public static bool AllowUpdate = true;
    
            
    
            public static void SocketConnect()
            {
                try
                {
                    if (!HeadClient.Connected)
                    {
                        HeadClient.Connect(endpoint);
                    }
                }
                catch (Exception ex)
                { }
            }
    
            public static void SocketClose()
            {
                if (HeadClient.Connected)
                {
                    HeadClient.Close();
                }
            }
    public static void ThreadGetSingleDownloadedFile(object data)   //object参数可以实现界面传入数据进行使用
            {
                string retMD5 = string.Empty;
                try
                {
                    HanleListItemClass formInter = data as HanleListItemClass;
    
    
                    XmlDocument aa = XmlHelper.BuildXmlDoc("CMD", "1", "1",
                     new List<HollXmlNode> { new HollXmlNode("ID","2",null),
                                            new HollXmlNode("STATE","127",null) });
                    //主要为了构建XML文件进行Socket的send操作
                    //构造后如下  <?xml version='1.0' encoding='utf-8'?><CMD code='1'  index='1'>
                    //                 <ID>2</ID>
                     //                <STATE>127</STATE></CMD>
    
    
                    byte[] sendaskbyte = Encoding.UTF8.GetBytes(aa.InnerXml.ToString());
                    int sendcount = 0;
    
    
                    try
                    {
                        sendcount = HeadClient.Send(sendaskbyte, sendaskbyte.Length, 0);
                    }
                    catch (Exception ex)
                    {
                        // return LOGIN_ERROR;
                    }
    
    
                    if (sendcount == 0)
                    {
                        //return LOGIN_ERROR;
                    }
    
    
    
    
                    int ret = SingleDownloadedFileWaitBack(formInter);
    
    
    
    
                }
                catch
                {
                    //return LOGIN_ERROR;
                }
            }
    
    
            public static int SingleDownloadedFileWaitBack(HanleListItemClass tItemclass)
            {
                byte[] RetData = new byte[36 * 1024];
                Array.Clear(RetData, 0, RetData.Length);
                int datalen = 0;
    
    
                try
                {
                    datalen = HeadClient.Receive(RetData);
    
    
                    if (datalen == 0)
                    {
                        return -1;
                    }
    
                    //接收到服务器返回的信息
                    string tcpdatastring = Encoding.UTF8.GetString(RetData).Replace("", " "); ;
    
    
                    //此处可以根据自己需求处理返回的信息 http://www.cnblogs.com/sosoft/
                   
                    return 0;
    
    
                }
                catch (Exception ex)
                {
                    return 0;
                }
            }
        }

     然后再界面调用的时候,我们只需要在事件中这么使用即可

     private void button1_Click(object sender, EventArgs e)   
    
        {  PublicSocket.SocketConnect();   
    
                ThreadPool.QueueUserWorkItem(new WaitCallback(SocketMethod.ThreadGetTotalState), this);     
    
      } 

    同时也把构建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 
     5         public static XmlDocument BuildXmlDoc(string xmltype, string code, string index, List<HollXmlNode> xmlnodes)
     6         {
     7             XmlDocument root = new XmlDocument();
     8             root.LoadXml(string.Format(xmlinit, xmltype, code, index));
     9 
    10             if (xmlnodes != null)
    11             {
    12                 for (int i = 0; i < xmlnodes.Count; i++)
    13                 {
    14                     XmlElement parentNode = root.CreateElement(xmlnodes[i].NodeName);
    15 
    16                     XmlText descText = root.CreateTextNode(xmlnodes[i].NodeValue);
    17                     parentNode.AppendChild(descText);
    18 
    19 
    20                     if (xmlnodes[i].NodeAtt != null)
    21                     {
    22                         if (xmlnodes[i].NodeAtt.Count > 0)
    23                         {
    24                             for (int j = 0; j < xmlnodes[i].NodeAtt.Count; j++)
    25                             {
    26                                 parentNode.SetAttribute(xmlnodes[i].NodeAtt[j].AttName, xmlnodes[i].NodeAtt[j].AttValue);
    27                             }
    28                         }
    29                     }
    30 
    31                     root.LastChild.AppendChild(parentNode);
    32                 }
    33             }
    34 
    35 
    36             return root;
    37         }
    38 
    39 
    40     }
     1 public class HollXmlNode
     2     {
     3         private string _nodename;
     4         private string _nodevalue;
     5         private List<HollXmlAttribute> _nodeatt;
     6 
     7 
     8         public HollXmlNode(string tnodename, string tnodevalue, List<HollXmlAttribute> tnodeatt)
     9         {
    10             _nodename = tnodename;
    11             _nodevalue = tnodevalue;
    12             _nodeatt = tnodeatt;
    13         }
    14 
    15 
    16         public string NodeName
    17         {
    18             get { return _nodename; }
    19             set { _nodename = value; }
    20         }
    21 
    22 
    23 
    24 
    25         public string NodeValue
    26         {
    27             get { return _nodevalue; }
    28             set { _nodevalue = value; }
    29         }
    30 
    31 
    32         public List<HollXmlAttribute> NodeAtt
    33         {
    34             get { return _nodeatt; }
    35             set { _nodeatt = value; }
    36         }
    37     }
    38 
    39 
    40     public class HollXmlAttribute
    41     {
    42         private string _attname;
    43         private string _attvalue;
    44 
    45 
    46         public HollXmlAttribute(string tname, string tvalue)
    47         {
    48             _attname = tname;
    49             _attvalue = tvalue;
    50         }
    51 
    52 
    53         public string AttName
    54         {
    55             get { return _attname; }
    56             set { _attname = value; }
    57         }
    58 
    59 
    60         public string AttValue
    61         {
    62             get { return _attvalue; }
    63             set { _attvalue = value; }
    64         }
    65     }
  • 相关阅读:
    Python数据结构与算法(几种排序)
    jquery元素节点操作
    Jquery事件委托
    Jquery事件冒泡
    jquery事件
    尺寸相关、滚动事件
    jquery属性操作
    jquery选择器
    JavaScript面向对象
    jQuery powerFloat万能浮动层下拉层插件
  • 原文地址:https://www.cnblogs.com/sosoft/p/3791630.html
Copyright © 2011-2022 走看看