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
}
|