1. 程式人生 > >C#socke通信t編程

C#socke通信t編程

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;
}
}
}
內容來自:越康體育

C#socke通信t編程