schangxiang@126.com
2025-11-04 ca398287db3f5ea01f03aac4a85edb13b28100a6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using XCommon.Log;
 
namespace XHandler.Class
{
    public class HttpServer
    {
        public static int BufferSize = 8192;
        public const string DeleteMethod = "DELETE";
        public const int NotFounded = 404;
        public const int BadRequest = 400;
        public const int NotImplemented = 501;
 
 
        private static HttpListener httplistener;
        public HttpServer()
        {
 
        }
 
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="content">内容</param>
        public static void CreateFileContent(string path, string content)
        {
            if (!string.IsNullOrEmpty(content))
            {
                UTF8Encoding utf8 = new UTF8Encoding(true);
                FileInfo fi = new FileInfo(path);
                var di = fi.Directory;
                if (!di.Exists)
                {
                    di.Create();
                }
                StreamWriter sw = new StreamWriter(path, false, utf8);
                sw.Write(content);
                sw.Close();
            }
        }
 
        public static string GetLocalIP()
        {
            try
            {
                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
                LoggerHelper.ErrorLog("ERROR:", ex);
                return "";
            }
        }
 
        //获取ip
        public static string GetIP()
        {
            string result = String.Empty;
            if (HttpContext.Current != null && HttpContext.Current.Session != null && HttpContext.Current.Session["IP"] != null)
            {
                result = HttpContext.Current.Session["IP"].ToString();
            }
            else
            {
                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (null == result || result == String.Empty)
                {
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
 
                if (null == result || result == String.Empty)
                {
                    result = HttpContext.Current.Request.UserHostAddress;
                }
 
                //if (null == result || result == String.Empty || !IsIP(result))
                //{
                //    return "0.0.0.0";
                //}
            }
            return result;
        }
 
        /// <summary>
        /// 初始化地址
        /// </summary>
        /// <param name="ip">IP</param>
        /// <param name="port">端口</param>
        /// <param name="fileName">文件名</param>
        /// <param name="content">内容</param>
        public static string Init(string ip, string port, string fileName, string content)
        {
            string server = $"http://{ip}:{port}/";
            //string server = "http://localhost:8081/"; 
 
            string folder = "UploadFolder";
            string uploadPath = AppDomain.CurrentDomain.BaseDirectory + folder;
            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }
 
            string pathStr = uploadPath + "\\" + fileName;
            CreateFileContent(pathStr, content);
 
            httplistener = new HttpListener();
            try
            {
                httplistener.Prefixes.Add(server);
                httplistener.Start();
                Console.WriteLine("server successfully runned");
 
                httplistener.BeginGetContext(Result, null);
 
                //LogConstant.logger.Print("[httpserver =]" + server + " 已启动");
                /*while (true)
                {
                    IHttpCommand command;
                    HttpListenerContext httplistenercontext = httplistener.GetContext();
                    string commandname = httplistenercontext.Request.HttpMethod;
 
                    
                }*/
                return server + folder + "/" + fileName;
            }
            catch (Exception ex)
            {
                LoggerHelper.ErrorLog("ERROR:", ex);
                //LogConstant.logger.Print("start httpserver exception:" + ex.ToString());
            }
            //finally
            //{
            //    httplistener.Close();
            //}
            return "";
        }
 
        public static void Stop()
        {
            httplistener.Close();
            httplistener = null;
        }
 
        private static void Result(IAsyncResult ar)
        {
            //当接收到请求后程序流会走到这里
 
            if (httplistener == null)
                return;
            //继续异步监听
            httplistener.BeginGetContext(Result, null);
 
            var guid = Guid.NewGuid().ToString();
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine($"接到新的请求:{guid},时间:{DateTime.Now.ToString()}");
            //获得context对象
            var context = httplistener.EndGetContext(ar);
            var request = context.Request;
            var response = context.Response;
            //如果是js的ajax请求,还可以设置跨域的ip地址与参数
            //context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//后台跨域请求,通常设置为配置文件
            //context.Response.AppendHeader("Access-Control-Allow-Headers", "ID,PW");//后台跨域参数设置,通常设置为配置文件
            //context.Response.AppendHeader("Access-Control-Allow-Method", "post");//后台跨域请求设置,通常设置为配置文件
            context.Response.ContentType = "text/plain;charset=UTF-8";//告诉客户端返回的ContentType类型为纯文本格式,编码为UTF-8
            context.Response.AddHeader("Content-type", "text/plain");//添加响应头信息
            context.Response.ContentEncoding = Encoding.UTF8;
            string returnObj = null;//定义返回客户端的信息
 
            IHttpCommand command = null;
            string commandname = request.HttpMethod;
 
            switch (commandname)
            {
                /*case WebRequestMethods.Http.Put:
                    command = new PutCmd();
                    Console.WriteLine("method PUT was called");
                    break;
                case DeleteMethod:
                    command = new DeleteCmd();
                    Console.WriteLine("method DELETE was called");
                    break;
                case WebRequestMethods.Http.Head:
                    command = new HeadCmd();
                    Console.WriteLine("method HEAD was called");
                    break;*/
                case WebRequestMethods.Http.Get:
                    command = new GetCmd();
                    Console.WriteLine("method GET was called");
                    break;
                default:
                    Console.WriteLine("Unrecognized Method!");
                    response.StatusCode = NotImplemented;
                    response.OutputStream.Close();
                    break;
            }
 
            if (command != null)
                command.Process(request, ref response);
 
        }
    }
 
    public class GetCmd : IHttpCommand
    {
        public void Process(HttpListenerRequest request, ref HttpListenerResponse response)
        {
            Stream output = response.OutputStream;
 
            var writer = new StreamWriter(output);
 
            string subPath = request.RawUrl.Substring(1);
            subPath = subPath.Replace('/', '\\');
            string fullPath = AppDomain.CurrentDomain.BaseDirectory + subPath;
 
            try
            {
                if (File.Exists(fullPath))
                {
                    Stream file = new FileStream(fullPath, FileMode.Open);
                    file.CopyTo(output, HttpServer.BufferSize);
                    file.Close();
                }
                else
                {
                    var directories = Directory.EnumerateFiles(fullPath);
 
                    foreach (var entry in directories)
                    {
                        writer.Write(JsonConvert.SerializeObject(entry));
                    }
                    writer.Flush();
                }
            }
            catch (FileNotFoundException ex)
            {
                LoggerHelper.ErrorLog("ERROR:", ex);
                response.StatusCode = HttpServer.NotFounded;
            }
            catch (DirectoryNotFoundException ex)
            {
                LoggerHelper.ErrorLog("ERROR:", ex);
                response.StatusCode = HttpServer.NotFounded;
            }
            catch
            {
                response.StatusCode = HttpServer.BadRequest;
            }
            finally
            {
                output.Close();
                writer.Dispose();
            }
        }
    }
 
 
}