using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace DTSClient
{
//关闭事件的委托
public delegate bool ConsoleCtrlDelegate(int dwCtrlType);
class Program
{
//捕获系统退出消息
[DllImport("kernel32.dll")]
static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine, bool Add);
private static Thread wait_connection_thread;
private static Thread write_Log_Info_thread;
private static Thread send_thread;
private static Thread getAllContent_thread;
private static ManualResetEvent alldone = new ManualResetEvent(false);
private static ManualResetEvent reciveDone = new ManualResetEvent(false);
private static UdpClient receivingUdpClient = new UdpClient(12001);
private static UdpClient sendUdpClient = new UdpClient();
private static ConsoleCtrlDelegate newDelegate = new ConsoleCtrlDelegate(HandlerRoutine);
private static List<string> temploginfo = new List<string>();
//获取网页数据是否完成
private static bool isEndGetWebData = false;
//所有网页数据
private static List<string> allInfo = new List<string>();
static void Main(string[] args)
{
write_Log_Info_thread = new Thread(new ThreadStart(writeLog));
write_Log_Info_thread.Start();
GC.KeepAlive(newDelegate);
SetConsoleCtrlHandler(newDelegate, true);
//启动等待线程
wait_connection_thread = new Thread(new ThreadStart(wait_connection));
wait_connection_thread.Start();
}
//关闭时候需要做的事情
public static bool HandlerRoutine(int CtrlType)
{
receivingUdpClient.Close();
sendUdpClient.Close();
recordLog("关闭退出代码:"+CtrlType);
return false;
}
//异步接收消息
public static void wait_connection()
{
try
{
while (true)
{
alldone.Reset();
receivingUdpClient.BeginReceive(waitSocket, receivingUdpClient);
alldone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
/// <summary>
/// 异步处理
/// </summary>
/// <param name="AR"></param>
public static void waitSocket(IAsyncResult AR)
{
try
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
UdpClient udpC = (UdpClient)AR.AsyncState;
Byte[] receiveBytes = udpC.EndReceive(AR, ref RemoteIpEndPoint);
alldone.Set();
string returnData = Encoding.GetEncoding("GB2312").GetString(receiveBytes);
recordLog("收到消息来自[" + RemoteIpEndPoint.Address.ToString() + "]的消息:" + returnData);
//调用处理
dealwithMsg(returnData, RemoteIpEndPoint.Address.ToString());
}
catch (Exception e)
{
recordLog(e.ToString());
}
}
public static void dealwithMsg(string msg,string toip)
{
string[] msgSp = msg.Split('|');
switch(msgSp[0])
{
case "0001":
recordLog("向["+toip+"响应消息5000");
send(toip, "5000");
break;
//得到DTS单号数据
case "0002":
recordLog("向["+toip+"响应消息5002,并开始获取网页内容");
send(toip, "5002");
//解析数据
if (msgSp.Length > 1)
{
//getAllWebData(msgSp[1].Split(','));
try
{
if (getAllContent_thread == null)
{
getAllContent_thread = new Thread(new ParameterizedThreadStart(getAllWebData));
}
if (getAllContent_thread.IsAlive)
{
recordLog("获取未完成,服务器要求重新获取");
getAllContent_thread.Abort();
getAllContent_thread = null;
getAllContent_thread = new Thread(new ParameterizedThreadStart(getAllWebData));
}
else
{
getAllContent_thread.Abort();
getAllContent_thread = null;
getAllContent_thread = new Thread(new ParameterizedThreadStart(getAllWebData));
}
getAllContent_thread.Start(msgSp[1].Split(','));
}
catch (Exception e) { recordLog(e.ToString()); }
}
break;
case "0003":
//完成
if (isEndGetWebData)
{
recordLog("向[" + toip + "响应消息5004,已经完成网页获取");
send(toip, "5004");
}
else
{
recordLog("向[" + toip + "响应消息5005,未完成网页获取");
send(toip, "5005");
}
break;
case "0004":
//将数据打包发送
try
{
if (send_thread == null)
{
send_thread = new Thread(new ParameterizedThreadStart(sendAllData));
}
if (send_thread.IsAlive)
{
recordLog("未完成的情况下重新服务器要求重发");
send_thread.Abort();
send_thread = null;
send_thread = new Thread(new ParameterizedThreadStart(sendAllData));
}
else
{
send_thread.Abort();
send_thread = null;
send_thread = new Thread(new ParameterizedThreadStart(sendAllData));
}
send_thread.Start(toip);
}
catch (Exception e) { recordLog(e.ToString()); }
break;
case "0007":
recordLog("来自[" + toip + "]的消息:" + msgSp[0] + "--再次启动发送数据");
reciveDone.Set();
break;
default:
recordLog("来自[" + toip + "]的消息:" + msgSp[0] + "--解析错误");
break;
}
}
/// <summary>
/// 发送所有数据
/// </summary>
/// <param name="toip"></param>
public static void sendAllData(object otoip)
{
string toip = (string)otoip;
//10记录一条整数发送
for (int i = 0; i < (allInfo.Count / 10); i++)
{
reciveDone.Reset();
string temp = "5006+" + allInfo.Count + "+10+";
for (int j = 0; j < 10; j++)
{
temp += allInfo[(i*10)+j] + "#";
}
send(toip,temp.Substring(0,temp.Length-1));
recordLog("向[" + toip + "响应消息["+((i*10)-10+10)+","+((i*10)-1+10)+"]" + temp);
reciveDone.WaitOne();
}
//剩余发送
int lastDtsInfo = allInfo.Count % 10;
if (lastDtsInfo != 0)
{
reciveDone.Reset();
string temp = "5006+" + allInfo.Count + "+" + lastDtsInfo + "+";
for (int i = 0; i < lastDtsInfo; i++)
{
temp += allInfo[(allInfo.Count - lastDtsInfo) + i] + "#";
}
send(toip, temp.Substring(0, temp.Length - 1));
recordLog("向[" + toip + "响应消息[" + ((allInfo.Count) - lastDtsInfo) + "," + (allInfo.Count-1).ToString() +"]"+ temp);
reciveDone.WaitOne();
}
//响应5008
recordLog("向[" + toip + "响应消息5008,完成所有数据发送");
send(toip,"5008");
send_thread = null;
}
/// <summary>
/// 获取数据
/// </summary>
/// <param name="allDtsId">dts单号数组</param>
public static void getAllWebData(object o_allDtsId)
{
allInfo.Clear();
isEndGetWebData = false;
string[] allDtsId = (string[])o_allDtsId;
for (int i = 0; i < allDtsId.Length; i++)
{
recordLog("开始获取[:" + allDtsId[i] + "]的内容");
string thiscontent = WebContent.getInfo(allDtsId[i]);
allInfo.Add(thiscontent);
recordLog(allDtsId[i] + "的内容:" + thiscontent);
Thread.Sleep(500);
}
isEndGetWebData = true;
}
/// <summary>
/// 消息发送
/// </summary>
/// <param name="toip">IP</param>
/// <param name="toport">Port</param>
/// <param name="content">内容</param>
public static void send(string toip, string content)
{
try
{
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(toip), 12001);
Byte[] data = Encoding.GetEncoding("GB2312").GetBytes(content);
sendUdpClient.Send(data, data.Length, ipEndPoint);
}
catch (Exception e)
{
recordLog(e.ToString());
}
}
/// <summary>
/// 日志记录
/// </summary>
/// <param name="log"></param>
public static void recordLog(string log)
{
string aa = DateTime.Now.ToString();
temploginfo.Add( aa+"\t" + log + "\r\n");
Console.WriteLine(log);
}
/// <summary>
/// 写日志
/// </summary>
public static void writeLog()
{
while (true)
{
Thread.Sleep(500);
lock (temploginfo)
{
for (int i = 0; i < temploginfo.Count; i++)
{
File.AppendAllText("mylog.log",temploginfo[i]);
}
temploginfo.Clear();
}
}
}
}
public class WebContent
{
public static string getInfo(string dtsId)
{
string dtsWebContent = getHtmlContent(dtsId.Trim());
string Processtitle = null;
string ProcessHaddeer = null;
string ProcessTime = null;
List<string>[] allPro=getProcess(dtsWebContent);
for (int i = 0; i < allPro[0].Count; i++)
{
Processtitle += allPro[0][i] + ",";
}
for (int i = 0; i < allPro[1].Count; i++)
{
ProcessHaddeer += allPro[1][i] + ",";
}
for (int i = 0; i < allPro[2].Count; i++)
{
ProcessTime += allPro[2][i] + ",";
}
try
{
return dtsId + "|" + getCurrentStatus(dtsWebContent) + "|" +
getCurrentHadder(dtsWebContent) + "|" + getSeriousLevel(dtsWebContent) + "|" +
getDutyTeam(dtsWebContent) + "|" + getCreateTime(dtsWebContent) + "|" +
Processtitle.Substring(0, Processtitle.Length - 1) + "|" +
ProcessHaddeer.Substring(0, ProcessHaddeer.Length - 1) + "|" +
ProcessTime.Substring(0, ProcessTime.Length - 1);
}
catch (Exception e)
{
return dtsId + "|" + getCurrentStatus(dtsWebContent) + "|" +
getCurrentHadder(dtsWebContent) + "|" + getSeriousLevel(dtsWebContent) + "|" +
getDutyTeam(dtsWebContent) + "|" + getCreateTime(dtsWebContent) + "|" +
"" + "|" +
"" + "|" +
"";
}
}
/// <summary>
/// 获取当前状态
/// </summary>
/// <param name="dtsWebContent">整个网页</param>
/// <returns></returns>
private static string getCurrentStatus(string dtsWebContent)
{
string str1 = WebContent.getKeyWordIndexs(dtsWebContent, "问题单当前状态\\s{1}.*\\s{1}.*\\s{1}.*\\s{1}.*\">", "</span>");
string str2 = WebContent.getKeyWordIndexs(dtsWebContent, "问题单当前状态\\s{1}.*\\s{1}.*\\s{1}.*\\s{1}.*\\s{1}.*\">", "</span>");
return str1 + " (" + str2 + ")";
}
/// <summary>
/// 获取当前处理人
/// </summary>
/// <param name="dtsWebContent">整个网页</param>
/// <returns></returns>
private static string getCurrentHadder(string dtsWebContent)
{
string str1 = WebContent.getKeyWordIndexs(dtsWebContent, "当前处理人\\s{1}.*\\s{1}.*\\s{1}.*\\s{1}.*\">", "</span>");
return str1;
}
/// <summary>
/// 获取严重程度
/// </summary>
/// <param name="dtsWebContent">整个网页</param>
/// <returns></returns>
private static string getSeriousLevel(string dtsWebContent)
{
string str1 = WebContent.getKeyWordIndexs(dtsWebContent, "严重程度\\s{1}.*\\s{1}.*\\s{1}.*\\s{1}.*\">", "<input");
return str1;
}
/// <summary>
/// 获取责任项目组
/// </summary>
/// <param name="dtsWebContent">整个网页</param>
/// <returns></returns>
private static string getDutyTeam(string dtsWebContent)
{
string str1 = WebContent.getKeyWordIndexs(dtsWebContent, "责任项目组\\s{1}.*\\s{1}.*\\s{1}.*\\s{1}.*\">", "<input");
return str1;
}
/// <summary>
/// 获取问题创建时间
/// </summary>
/// <param name="dtsWebContent">整个网页</param>
/// <returns></returns>
private static string getCreateTime(string dtsWebContent)
{
string str1 = WebContent.getKeyWordIndexs(dtsWebContent, "问题创建时间\\s{1}.*\\s{1}.*\\s{1}.*\\s{1}.*\">", "</span>");
return str1;
}
/// <summary>
/// 获取流程
/// </summary>
/// <param name="dtsWebContent">整个网页</param>
/// <returns></returns>
private static List<string>[] getProcess(string dtsWebContent)
{
List<string> titleList = new List<string>();
List<string> lastHandlerList = new List<string>();
List<string> lastTimeList = new List<string>();
Regex regTitle = new Regex(@"(?is)(?<=<div class=""divNodeBizInfoTitleLeft""[^>]*?>)[^<>]*?(?=<span)");
Regex regLastHandler = new Regex(@"(?<=最后处理人:).*(?=\s )");
Regex regLastTime = new Regex(@"(?<=最后处理时间:).*(?=\))");
MatchCollection mcTitle=regTitle.Matches(dtsWebContent);
MatchCollection mcLastHandler=regLastHandler.Matches(dtsWebContent);
MatchCollection mcLastTime=regLastTime.Matches(dtsWebContent);
foreach (Match m in mcTitle)
{
titleList.Add(m.Value.Trim());
}
foreach (Match m in mcLastHandler)
{
lastHandlerList.Add(m.Value.Trim());
}
foreach (Match m in mcLastTime)
{
lastTimeList.Add(m.Value.Trim());
}
List<string>[] a =new List<string>[3];
a[0] = titleList;
a[1] = lastHandlerList;
a[2] = lastTimeList;
return a;
}
/// <summary>
/// 获取该类中所有匹配项的索引
/// </summary>
/// <param name="str"></param>
/// <param name="keyWord"></param>
/// <returns></returns>
private static string getKeyWordIndexs(string dtsWebContent, string startKeyWord,string endKeyWord)
{
string retStr = null;
try
{
Regex startR = new Regex(startKeyWord);
Regex endR = new Regex(endKeyWord);
Match stratM = startR.Match(dtsWebContent);
Match endM = endR.Match(dtsWebContent, stratM.Index + stratM.Value.Length);
if (stratM.Value != "" && endM.Value != "" && (stratM.Index < endM.Index))
{
retStr = dtsWebContent.Substring((stratM.Index + stratM.Value.Length), endM.Index - (stratM.Index + stratM.Value.Length));
}
else
{
retStr = "未发现需要的字符串";
}
}
catch (Exception e) { Console.WriteLine(e.ToString()); }
return retStr;
}
/// <summary>
/// 获取网页信息
/// </summary>
/// <param name="dtsID">DTS单号</param>
/// <returns>整个网页</returns>
private static string getHtmlContent(String dtsID)
{
HttpWebRequest myrequest = (HttpWebRequest)HttpWebRequest.Create(@"http://dts.huawei.com/net/dts/DTS/DTSWorkFlowPage.aspx?No=" + dtsID);
myrequest.Headers.Add("Accept-Language", "zh-cn");
myrequest.Credentials = CredentialCache.DefaultCredentials;
myrequest.PreAuthenticate = true;
myrequest.Method = "GET";
myrequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, */*";
myrequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; WOW64; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET4.0C; .NET4.0E)";
myrequest.KeepAlive = true;
HttpWebResponse myresponse = (HttpWebResponse)myrequest.GetResponse();
StreamReader stR = new StreamReader(myresponse.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
return stR.ReadToEnd();
}
}
}