C # TCP Socket communication Basics

Source: Internet
Author: User

Socket communication is essential for network communication programs.

Therefore, we need a set of established and simple communication procedures.

As follows:

<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 Tcp Client (); 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_CODE ERROR = 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) // The object parameter can be used to input data on the interface. {string retMD5 = string. empty; try {HanleListItemClass formInter = data as HanleListItemClass; XmlDocument aa = XmlHelper. buildXmlDoc ("CMD ", "1", "1", new List <fig node> {new fig node ("ID", "2", null), new fig node ("STATE", "127 ", null)}); // mainly used to build an XML file and perform the send operation on the Socket. // The structure is as follows <? 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;} // receives the information returned by the Server string tcpdatastring = Encoding. UTF8.GetString (RetData ). replace ("\ 0", ""); // here you can handle the returned information http://www.cnblogs.com/sosoft/ return 0;} catch (Exception ex) {return 0 ;}}}

 

Before calling the interface, we only need to use it in the event.

 

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

 

At the same time, we also share the classes for Building XML to make the encoding easier.

 

 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 NodeName17         {18             get { return _nodename; }19             set { _nodename = value; }20         }21 22 23 24 25         public string NodeValue26         {27             get { return _nodevalue; }28             set { _nodevalue = value; }29         }30 31 32         public List<HollXmlAttribute> NodeAtt33         {34             get { return _nodeatt; }35             set { _nodeatt = value; }36         }37     }38 39 40     public class HollXmlAttribute41     {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 AttName54         {55             get { return _attname; }56             set { _attname = value; }57         }58 59 60         public string AttValue61         {62             get { return _attvalue; }63             set { _attvalue = value; }64         }65     }

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.