• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

c#TCPSocket通讯基础

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

在做网络通讯方面的程序时,必不可少的是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("\0", " "); ;


                //此处可以根据自己需求处理返回的信息 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     }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#中哈希表(HashTable)的用法详解发布时间:2022-07-13
下一篇:
C#文件流合并(未测试是否可用)发布时间:2022-07-13
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap