首页 > 技术文章 > 3分钟搞定一个简单的HTTP服务器

daluo 2016-08-28 19:07 原文

先上代码

[C#] 
 
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
 
 
namespace 异步http
{
    class Program
    {
        static HttpListener sSocket = null;
        static MySqlConnection mycon;
        static string host = "localhost";
        static string database = "test";
        static string id = "root";
        static string pwd = "qq001255552";
        static void Main(string[] args)
        {
            SetConsoleCtrlHandler(cancelHandler, true);
            sSocket = new HttpListener();
            sSocket.Prefixes.Add("http://*:7788/");
            sSocket.Start();
            string constr = string.Format("Server = {0};port={4};Database = {1}; User ID = {2}; Password = {3};", host, database, id, pwd,"3306");
            mycon = new MySqlConnection(constr);
            mycon.Open();
            sSocket.BeginGetContext(new AsyncCallback(GetContextCallBack), sSocket);
            Console.Read();
        }
 
        static void GetContextCallBack(IAsyncResult ar)
        {
            try
            {
                sSocket = ar.AsyncState as HttpListener;
                HttpListenerContext context = sSocket.EndGetContext(ar);
                sSocket.BeginGetContext(new AsyncCallback(GetContextCallBack), sSocket);
                HttpListenerRequest request = context.Request;
                HttpListenerResponse response = context.Response;
                Stream strem = request.InputStream;
                StreamReader reader = new StreamReader(strem,Encoding.UTF8);
                  
                string sql = reader.ReadToEnd();
                sql = System.Web.HttpUtility.UrlDecode(sql);
                reader.Close();
                strem.Close();
                sql = sql.Split('=')[1];
                Console.WriteLine( "内容:" + sql);
                switch (sql.Split('=')[0])
                {
                    case "update":
 
                        break;
                    case "selete":
                        break;
 
                    default:
                        break;
                }
 
 
                MySqlDataAdapter adptr = new MySqlDataAdapter(sql,mycon);//Adepter对象
                DataSet ds = new DataSet();//DataSet对象
                adptr.Fill(ds, "name");//填充DataSet 并为当前表命名
                DataTable rdr = ds.Tables[0];
                string send = "{";
                foreach (DataRow item in rdr.Rows)
                {
                    foreach (DataColumn t in rdr.Columns)
                    {
                        send += item[t]+":";
                    }
                    send += ",";
                }
                 send += "}";
                byte[] buffer = Encoding.UTF8.GetBytes("你好,我是大罗,你查询结果是——" + send);
                response.ContentLength64 = buffer.Length;
                Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
                response.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
 
        #region 关闭方法
        public delegate bool ControlCtrlDelegate(int CtrlType);
        [System.Runtime.InteropServices.DllImport("kernel32.dll")]
        private static extern bool SetConsoleCtrlHandler(ControlCtrlDelegate HandlerRoutine, bool Add);
        private static ControlCtrlDelegate cancelHandler = new ControlCtrlDelegate(HandlerRoutine);
 
        public static bool HandlerRoutine(int CtrlType)
        {
            switch (CtrlType)
            {
                case 0:
                    Console.WriteLine("0工具被强制关闭"); //Ctrl+C关闭 
                    sSocket.Close();
                    break;
                case 2:
                    Console.WriteLine("2工具被强制关闭");//按控制台关闭按钮关闭 
                    sSocket.Close();
                    break;
            }
            Console.ReadLine();
            return false;
        }
 
    }
    #endregion
}

  奥,首先你需要用VS新建一个 控制台应用程序 然后 copy 然后 run
还有。。。 你需要装上个 数据库  推荐使用mysql
访问服务器的话 直接使用 unity的WWW的form表单就行  

这玩意性能还不错 瞬间并发来个几千没问题  在大就没测试过了 一般小游戏搞个排行榜  登陆验证什么的 也没多少并发,稳定性也没啥问题 巨硬都封装好了(我对巨硬还是挺看好的)
   有问题追问哈

推荐阅读