using HDLMonitorService.Entity;
|
using HDLMonitorService.Helper;
|
using Newtonsoft.Json;
|
using System;
|
using System.Collections.Generic;
|
using System.Configuration;
|
using System.Linq;
|
using System.Messaging;
|
using System.Net;
|
using System.Text;
|
using System.Threading;
|
using System.Threading.Tasks;
|
|
namespace HDLMonitorService
|
{
|
public class ListenerAlarm
|
{
|
static HttpListener httpobj;
|
|
public static void Listener()
|
{
|
//提供一个简单的、可通过编程方式控制的 HTTP 协议侦听器。此类不能被继承。
|
httpobj = new HttpListener();
|
//定义url及端口号,通常设置为配置文件
|
httpobj.Prefixes.Add($"http://+:{ConfigurationManager.AppSettings["ListenerAlarmProt"].ToString()}/");
|
//启动监听器
|
httpobj.Start();
|
//异步监听客户端请求,当客户端的网络请求到来时会自动执行Result委托
|
//该委托没有返回值,有一个IAsyncResult接口的参数,可通过该参数获取context对象
|
httpobj.BeginGetContext(Result, null);
|
}
|
|
private static async void beginGetContext()
|
{
|
try
|
{
|
//当接收到请求后程序流会走到这里
|
//继续异步监听
|
httpobj.BeginGetContext(Result, null);
|
}
|
catch
|
{
|
await System.Threading.Tasks.Task.Delay(10);
|
//继续异步监听
|
beginGetContext();
|
}
|
}
|
private static void Result(IAsyncResult ar)
|
{
|
beginGetContext();
|
|
//获得context对象
|
var context = httpobj.EndGetContext(ar);
|
context.Response.ContentEncoding = Encoding.UTF8;
|
try
|
{
|
if (context.Request.InputStream != null)
|
{
|
var byteList = new List<byte>();
|
var byteArr = new byte[1024 * 2];
|
int readLen = 0;
|
int len = 0;
|
//接收客户端传过来的数据并转成字符串类型
|
do
|
{
|
readLen = context.Request.InputStream.Read(byteArr, 0, byteArr.Length);
|
len += readLen;
|
byteList.AddRange(byteArr);
|
} while (readLen != 0);
|
|
var data = Encoding.UTF8.GetString(byteList.ToArray(), 0, len);
|
//处理客户端发送的请求并返回处理信息
|
var info = JsonConvert.DeserializeObject<MqAlarmReqPack>(data);
|
Process(info);
|
}
|
}
|
catch { }
|
var result = new byte[] { };
|
using (var stream = context.Response.OutputStream)
|
{
|
//把处理信息返回到客户端
|
stream.Write(result, 0, result.Length);
|
}
|
}
|
|
private static void Process(MqAlarmReqPack info)
|
{
|
try
|
{
|
AlarmHp.ApplicationAlarm(info.ServiceName, info.AlarmType, info.Content, info.Address, info.Title);
|
}
|
catch (Exception ex) { LogHp.WriteLog("消息队列异常", Newtonsoft.Json.JsonConvert.SerializeObject(ex)); }
|
}
|
}
|
}
|