在做網絡通訊方面的程序時,必不可少的是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 }