创建一个简单的HTTP服务(自动查找未使用的端口)

            var t = new Thread(new ThreadStart(() => {
HttpListener listener = new HttpListener();
var prefix = string.Format("http://localhost:{0}/", port);
listener.Prefixes.Add(prefix);
listener.Start();
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, , buffer.Length);
output.Close();
listener.Stop();
}));
t.Start();

using System.Net;

        static int GetPort()
{
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
var port = ;
var flag = true;
while(flag)
{
flag = ipEndPoints.Any(p => { return p.Port == ; });
if (flag)
{
port += ;
if(port == )
{
MessageBox.Show("端口都被占用了,请联系管理员");
flag = false;
Environment.Exit();
}
}
else
{
flag = false;
break;
}
}
return port;
}
上一篇:生活life


下一篇:SQL2043N 与 linux的randomize_va_space特性