C#socke通信t编程

时间:2017-07-02 13:18:04   收藏:0   阅读:485
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Xml;
using JHTY.entity;
using System.Threading;
using System.Windows.Forms;

namespace www.xinduofen.com
{
    class SocketServerPort
    {
        private static Thread thread = new Thread(new ThreadStart(uploadTestData));
        
        /// <summary>
        /// 启动单发服务函数
        /// </summary>
        public static void startServer() {
            SocketServerPort.thread.IsBackground = true;//设置为后台线程
            SocketServerPort.thread.Start();
        }

        /// <summary>
        /// 退出单发服务函数
        /// </summary>
        public static void stopServer() {
            SocketServerPort.thread.Abort();
        }
        
        
        /// <summary>
        /// 单发服务函数
        /// </summary>
        private static void uploadTestData()//TCP、9050、XML数据格式、UTF-8编码、V1.0
        {
            while (true)
            {
                Socket newsock = null;
                try
                {
                    int recv;//用于表示数据流长度
                    byte[] data = new byte[1024];//用于缓存发送的信息,通过socket传递的信息必须为字节数组
                    IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//本机预使用的IP和端口
                    newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    newsock.Bind(ipep);//绑定
                    newsock.Listen(10);//监听
                    while (true)
                    {
                        Socket client = null;
                        try
                        {
                            client = newsock.Accept();//当有可用的客户端连接尝试时执行,并返回一个新的socket,用于与客户端之间的通信
                            client.ReceiveTimeout = 1000 * 5;//接受数据流的超时时间为‘5S’
                            client.SendTimeout = 1000 * 30;//发送数据流的超时时间为‘30S’
                            FileStream file = new FileStream("testId.xml", FileMode.Create);//临时文件
                            while ((recv = client.Receive(data)) > 0)
                            {
                                file.Write(data, 0, recv);
                                file.Flush();
                            }
                            file.Close();

                            XmlDocument doc = new XmlDocument();
                            using (StreamReader sr = new StreamReader("testId.xml", Encoding.UTF8))
                            {
                                doc.Load(sr);//加载Xml文件
                                XmlElement rootElem = doc.DocumentElement;//获取根节点
                                XmlNodeList personNodes = rootElem.GetElementsByTagName("testId"); //获取testId子节点集合
                                foreach (XmlNode node in personNodes)
                                {
                                    string testId = ((XmlElement)node).InnerText;//测试编号

                                    JHTY.dao.StudentDao sd = new JHTY.dao.StudentDao();
                                    Student st = null;
                                    if (testId != null && !"".Equals(testId))
                                    {
                                        st = new Student();
                                        st.setId(testId);
                                    }
                                    XmlDocument xmlDoc = new XmlDocument();
                                    XmlNode typeNode = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");//创建类型声明节点
                                    xmlDoc.AppendChild(typeNode);
                                    XmlNode root = xmlDoc.CreateElement("root");//创建根节点
                                    xmlDoc.AppendChild(root);
                                    List<Student> listST = sd.search(st,true,null);//查询测试者信息
                                    if (listST != null && listST.Count>0)
                                    {
                                        foreach (Student stu in listST)//迭代所有人的测试数据
                                        {
                                            XmlNode person = CreateNode(xmlDoc, root, "person", null);;//创建一个人的节点
                                            CreateNode(xmlDoc, person, "testId", stu.getId());

                                            if (stu.getItemTemplet() != null && stu.getItemTemplet().Count>0)
                                            {
                                                foreach (System.Collections.DictionaryEntry de in stu.getItemTemplet())
                                                {
                                                    string itemId = ((string)de.Key).Replace("itemTemplet", "");//项目编号
                                                    ItemTemplet it = (ItemTemplet)de.Value;

                                                    XmlNode item = CreateNode(xmlDoc, person, "item", null);
                                                    CreateNode(xmlDoc, item, "itemId", itemId);
                                                    CreateNode(xmlDoc, item, "itemScore", it.getGrade().ToString());
                                                }
                                            }
                                        }
                                    }
                                    xmlDoc.Save("manyPeople.xml");

                                    using (FileStream result = new FileStream("manyPeople.xml", FileMode.Open))
                                    {
                                        while ((recv = result.Read(data,0,1024)) > 0)
                                        {
                                            client.Send(data, 0, recv, SocketFlags.None);
                                        }
                                    }

                                    break;//只需要进行一次就退出
                                }
                            }
                            if (File.Exists("testId.xml"))
                            {
                                File.Delete("testId.xml");
                            }
                            if (File.Exists("manyPeople.xml"))
                            {
                                File.Delete("manyPeople.xml");
                            }
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("服务端口处理客户端请求时异常退出!");
                            //MessageBox.Show("服务端口处理客户端请求时异常退出!");

                        }
                        finally {
                            if (client!=null)
                            {
                                client.Shutdown(SocketShutdown.Both);
                                client.Close();
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("服务端口异常退出!");
                    //MessageBox.Show("服务端口异常退出!");
                }
                finally
                {
                    if (newsock!=null)
                    {
                        newsock.Shutdown(SocketShutdown.Both);
                        newsock.Close();
                    }
                }
                Console.WriteLine("服务端口重新启动!");
                //MessageBox.Show("服务端口重新启动!");
            }
        }

        /// <summary>
        /// 创建新节点
        /// </summary>
        /// <param name="xmldoc"></param>
        /// <param name="parentnode"></param>
        /// <param name="nodeName"></param>
        /// <param name="nodeValue"></param>
        private static XmlNode CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string nodeName, string nodeValue)
        {
            XmlNode node = xmlDoc.CreateElement(nodeName);
            if (nodeValue != null && !"".Equals(nodeValue))
            {
                node.InnerText = nodeValue;
            }
            parentNode.AppendChild(node);

            return node;
        }
    }
}
内容来自:越康体育
评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!