public class SendMqService
{
private static bool isExcute = true;
private static HttpListener listener = new HttpListener();
public static void Start()
{
System.Threading.ThreadPool.QueueUserWorkItem(w => Excute());//单独开启一个线程执行监听消息
} private static void Excute()
{
if (HttpListener.IsSupported)
{
if (!listener.IsListening)
{
listener.Prefixes.Add(AppSetingHelper.GetValue("SendMqAddress")); //添加需要监听的url,如:http://192.016.0.1:8888
listener.Start(); //开始监听端口,接收客户端请求
}
while (isExcute)
{
try
{
//阻塞主函数至接收到一个客户端请求为止
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response; var reader = new StreamReader(request.InputStream);
var mqMsg = reader.ReadToEnd();
var responseString = string.Empty; // 执行其他业务逻辑
//***************** responseString = JsonConvert.SerializeObject(new { code = , msg = "发送成功" });
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
//对客户端输出相应信息.
response.ContentLength64 = buffer.Length;
using (System.IO.Stream output = response.OutputStream)
{
output.Write(buffer, , buffer.Length);
}
}
catch (Exception exceotion)
{
Logger.Error("处理消息异常", exceotion);
}
}
}
else
{
Logger.Info("系统不支持HttpListener");
}
} public static void Stop()
{
isExcute = false;
if (listener.IsListening)
listener.Stop();
}
}
}
服务启动时需要启动监听,服务停止时需要停止监听
protected override void OnStart(string[] args)
{
SendMqService.Start();
} protected override void OnStop()
{
//停止监听
SendMqService.Stop();
}