C#using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace 保持程序最新服务端
{
internal class Program
{
static System.Net.HttpListener httpListener = new HttpListener();
static void Main(string[] args)
{
string IpAddress = "";
string port = "";
try
{
IpAddress= File.ReadAllText("set\\IpAddress.txt");
port = File.ReadAllText("set\\port.txt");
}
catch (Exception ep)
{
}
Console.WriteLine("IpAddress:" + IpAddress + "port:" + port);
httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
httpListener.Prefixes.Add("http://" + IpAddress + ":"+port+"/");
httpListener.Start();
Thread thread = new Thread(HttpListen);
thread.Start();
}
static public void HttpListen()
{
while (true)
{
Console.WriteLine("开始监听");
HttpListenerContext httpListenerContext = httpListener.GetContext();
new Thread(new ThreadStart(delegate
{
try
{
using (StreamWriter writer = new StreamWriter(httpListenerContext.Response.OutputStream, Encoding.GetEncoding("GB2312")))
{
string urldata = httpListenerContext.Request.RawUrl.ToString();
HttpData httpData = new HttpData();
httpData.load(urldata);
httpListenerContext.Response.StatusCode = 200;
if (httpData.cmd.Equals("chaxun"))
{
string sendtemp = "";
try
{
string[] filelist = Directory.GetFiles("app\\"+ httpData.message+"\\");
sendtemp = filelist[0];
}
catch(Exception e)
{
}
send(writer, sendtemp);
Console.WriteLine("响应"+ httpData.message+ "的查询命令,结果是"+ sendtemp);
}
else if (httpData.cmd.Equals("download"))
{
string[] filelist = Directory.GetFiles("app\\" + httpData.message + "\\");
string filename = filelist[0];
byte[] sendtemp = File.ReadAllBytes(filename);
writer.BaseStream.Write(sendtemp, 0, sendtemp.Length);
writer.Close();
// writer.Write(sendtemp);
Console.WriteLine("响应" + httpData.message + "的下载命令");
}
else
{
string sendtemp = "null";
send(writer, sendtemp);
}
writer.Close();
}
}
catch (Exception spe)
{
}
})).Start();
}
}
static private void send(StreamWriter writer, string sendtemp)
{
try
{
writer.Write(sendtemp);
}
catch (Exception e)
{
}
}
static private void send(StreamWriter writer, byte[] sendtemp)
{
try
{
writer.Write(sendtemp);
}
catch (Exception e)
{
}
}
}
class HttpData
{
public string cmd = "";
public string message = "";
public string date = "";
public string name = "";
public void load(string data)
{
string[] data_sp = data.Split('/');
for (int cnt = 0; cnt < data_sp.Count(); cnt++)
{
switch (data_sp[cnt].Split('=')[0])
{
case "cmd":
cmd = data_sp[cnt].Split('=')[1];
break;
case "message":
message = data_sp[cnt].Split('=')[1];
break;
case "date":
date = data_sp[cnt].Split('=')[1];
break;
case "name":
name = data_sp[cnt].Split('=')[1];
break;
}
}
}
}
}
本文作者:Kellermen
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!