在很多开发当中,都需要监听本地端口,并作出响应
使用.net winform 可轻松的完成该功能
需要使用到 HttpListener 监听类
第一步: 初始化实体
internal static void ListenerStart(int port)
{
if (httpListener != null) return;
httpListener = new System.Net.HttpListener();
httpListener.Prefixes.Add("http://+:" + port.ToString() + "/");
httpListener.Start();//开始监听
//开始检索,定义异步回调
for (var i = 0; i < 20; i++) httpListener.BeginGetContext(ReceiveProcess, null);
}
第二步: 回调函数
static void ReceiveProcess(IAsyncResult ia)
{
System.Net.HttpListenerContext hlc;
try { hlc = httpListener.EndGetContext(ia); }//完成检索
catch (Exception e) { return; }
try
{
hlc.Response.Headers.Clear();
hlc.Response.StatusCode = 200;
hlc.Response.Headers["Server"] = hlc.Request.UserHostName;
hlc.Response.Headers["Last-Modified"] = DateTime.Now.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", System.Globalization.CultureInfo.CreateSpecificCulture("en-US"));
hlc.Response.Headers["Cache-Control"] = "max-age=31536000";
string response = "<!DOCTYPE html><html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta charset=\"utf-8\" /><title>ggbig.com本地监控测试</title></head><body>";
response += "给您点响应:" + DateTime.Now.ToString() + "<br/>";
response += "处理结果值:" + (new Random().Next(1000, 9999)).ToString();
response += "</body></html>";
if (response != null)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(response);
hlc.Response.OutputStream.Flush();
hlc.Response.Headers.Clear();
hlc.Response.ContentLength64 = bytes.Length;
hlc.Response.OutputStream.Write(bytes, 0, bytes.Length);
}
}
catch (ObjectDisposedException) { hlc.Response.StatusCode = 500; }
catch (System.Net.HttpListenerException) { hlc.Response.StatusCode = 500; }
catch (Exception e) { hlc.Response.StatusCode = 500; }
finally
{
hlc.Response.OutputStream.Flush();
hlc.Response.OutputStream.Close();
hlc.Response.OutputStream.Dispose();
hlc.Response.Close();
httpListener.BeginGetContext(ReceiveProcess, null);
}
}
第三步: 停止处理
internal static void ListenerEnd()
{
if (httpListener != null)
{
httpListener.Stop();
httpListener.Abort();
httpListener.Close();
httpListener = null;
}
}
以上3个步骤便可轻松监听电脑的本地端口,也可以写成服务,这样电脑每次重启后,便可直接监听.