Socket 处理接受消息类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.Xml; using System.Windows.Forms; namespace TransmissionLine.PublicClass { public class ClientConnection { public static Socket c; static string strALARMTYPE = "";//报警类型 static string strRecord = "";//报警级别 static string strALARMTIME = "";//报警时间 static string strLINENAME = "";//线路名 static string strSTRAINNAME = "";//耐张段 static string strSPANNAME = "";//档距段 static string strALARMVALUE = "";//报警值 /// <summary> /// 接受从服务器返回的信息 /// </summary> public static string recvStr = ""; public static void ClientPractice() {//客户端 try { int port = 2000; string host = "127.0.0.1"; /**/ ///创建终结点EndPoint IPAddress ip = IPAddress.Parse(host); //IPAddress ipp = new IPAddress("127.0.0.1"); IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndpoint实例 /**/ ///创建socket并连接到服务器 c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建Socket //Console.WriteLine("Conneting…"); c.Connect(ipe);//连接到服务器 } catch { } } public static void ClientAccept() {//客户端接受信息 byte[] recvBytes = new byte[1024]; //int int bytes=0; try { while (true) { bytes = 0; bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息 if (bytes <= 0) { System.Threading.Thread.Sleep(10);//设置休眠时间 continue; } //recvStr = Encoding.ASCII.GetString(recvBytes, 0, bytes); //接收中文 recvStr = Encoding.Unicode.GetString(recvBytes, 0, bytes); System.Windows.Forms.MessageBox.Show(recvStr); insertALARM(); if (recvStr != "") {//有消息跳出对话框 AlertingSignal ls = new AlertingSignal(); ls.ShowDialog(); } System.Threading.Thread.Sleep(10);//设置休眠时间 } } //catch //{ // System.Windows.Forms.MessageBox.Show("未连接服务器!","友情提示"); //} catch (ArgumentNullException e) { MessageBox.Show(e.ToString()); c.Close(); } catch (SocketException e) { //MessageBox.Show("未连接服务器!", "友情提示"); c.Close(); } } /// <summary> /// 插入报警表 /// </summary> public static void insertALARM() { //int amLength = 0; string str = ""; string temp = ""; if (PublicClass.ClientConnection.recvStr != "") {//报警信息不为空时 str = PublicClass.ClientConnection.recvStr; //得到HC1;2010-08-06 10:43:20;剑川线;T47-T80;T20-T59;900End temp = str.Remove(0, str.IndexOf(":")+1); strALARMTYPE = temp.Substring(0, temp.IndexOf(";")-1);//获得报警类型 strRecord = temp.Substring(strALARMTYPE.Length, 1);//获得报警级别 //2010-08-06 10:43:20;剑川线;T47-T80;T20-T59;900End temp = temp.Remove(0, temp.IndexOf(";")+1); strALARMTIME = temp.Substring(0,temp.IndexOf(";"));//获得报警时间 //剑川线;T47-T80;T20-T59;900End temp = temp.Remove(0, temp.IndexOf(";") + 1); strLINENAME = temp.Substring(0, temp.IndexOf(";"));//线路名 //T47-T80;T20-T59;900End temp = temp.Remove(0,temp.IndexOf(";")+1); strSTRAINNAME = temp.Substring(0, temp.IndexOf(";"));//耐张段 //T20-T59;900End temp = temp.Remove(0, temp.IndexOf(";") + 1); strSPANNAME = temp.Substring(0, temp.IndexOf(";"));//档距段 //900End temp = temp.Remove(0, temp.IndexOf(";") + 1); strALARMVALUE = temp.Substring(0, temp.IndexOf("E"));//报警值 insertXml(); } } /// <summary> /// 插入xml文档(报警记录) /// </summary> public static void insertXml() { //string strALARMTYPE = "";//报警类型 //string strRecord = "";//报警级别 //string strALARMTIME = "";//报警时间 //string strLINENAME = "";//线路名 //string strSTRAINNAME = "";//耐张段 //string strSPANNAME = "";//档距段 //string strALARMVALUE = "";//报警值 int maxvalue=0; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(Application.StartupPath + "//AlarmRecord.xml"); XmlNode root = xmlDoc.SelectSingleNode("fathernode");//<fathernode> XmlNodeList nodelist=root.ChildNodes; XmlElement xeTotal = xmlDoc.CreateElement("ALARMTable");//创建表 maxvalue = nodelist.Count + 1;//获得最大编号 xeTotal.SetAttribute("id",maxvalue.ToString()); //表中的属性 XmlElement xe1 = xmlDoc.CreateElement("ALARMTIME");//创建节点<ALARMTIME> xe1.InnerText = strALARMTIME; xeTotal.AppendChild(xe1); XmlElement xe2 = xmlDoc.CreateElement("LINENAME");//创建节点<LINENAME> xe2.InnerText = strLINENAME; xeTotal.AppendChild(xe2); XmlElement xe3 = xmlDoc.CreateElement("STRAINNAME");//创建节点<STRAINNAME> xe3.InnerText = strSTRAINNAME; xeTotal.AppendChild(xe3); XmlElement xe4 = xmlDoc.CreateElement("SPANNAME");//创建节点<SPANNAME> xe4.InnerText = strSPANNAME; xeTotal.AppendChild(xe4); XmlElement xe5 = xmlDoc.CreateElement("ALARMVALUE");//创建节点<ALARMVALUE> xe5.InnerText = strALARMVALUE; xeTotal.AppendChild(xe5); XmlElement xe6 = xmlDoc.CreateElement("ALARMTYPE");//创建节点<ALARMTYPE> xe6.InnerText = strALARMTYPE; xeTotal.AppendChild(xe6); XmlElement xe7 = xmlDoc.CreateElement("Record");//创建节点<Record> xe7.InnerText = strRecord; xeTotal.AppendChild(xe7); root.AppendChild(xeTotal); xmlDoc.Save(Application.StartupPath + "//AlarmRecord.xml"); } } } dpmain 主界面开启心跳调用Socket 处理接受消息类 private void timer1_Tick(object sender, EventArgs e) { //客户端调用服务器 if (AlertingSignal.Alarmessage == 0) { PublicClass.ClientConnection.ClientPractice(); thread = new Thread(new ThreadStart(PublicClass.ClientConnection.ClientAccept)); thread.Start();//启动线程 } else { return; } } 写一个控制台应用程序(服务器) 模拟 装置发来的短消息 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace SocketCodeTest { class Program { static void Main(string[] args) { int port = 2000; string host = "127.0.0.1"; /**/ ///创建终结点(EndPoint) IPAddress ip = IPAddress.Parse(host);//把ip地址字符串转换为IPAddress类型的实例 IPEndPoint ipe = new IPEndPoint(ip, port);//用指定的端口和ip初始化IPEndPoint类的新实例 /**/ ///创建socket并开始监听 Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket对像,如果用udp协议,则要用SocketType.Dgram类型的套接字 s.Bind(ipe);//绑定EndPoint对像(2000端口和ip地址) s.Listen(0);//开始监听 Console.WriteLine("等待客户端连接"); /**/ ///接受到client连接,为此连接建立新的socket,并接受信息 Socket temp = s.Accept();//为新建连接创建新的socket Console.WriteLine("建立连接"); string recvStr = "ALARM:HC1;2010-08-06 10:43:20;剑川线;T47-T80;T20-T59;900End"; //byte[] recvBytes = new byte[1024]; //int bytes; //bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息 //recvStr += Encoding.Unicode.GetString(recvBytes, 0, bytes); /**/ ///给client端返回信息 Console.WriteLine("server get message:{0}", recvStr);//把客户端传来的信息显示出来 //string sendStr = "ALARM "; byte[] bs = Encoding.Unicode.GetBytes(recvStr); temp.Send(bs, bs.Length, 0);//返回信息给客户端 temp.Close(); s.Close(); Console.ReadLine(); } } }