MYWebServer

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.IO;

namespace TrialSystem
{
    /// <summary>
    /// 读取到正确的配置信息后调用
    /// </summary>
    public class MYWebServer
    {
        #region 直播的笔录 (笔录内容实时更新这个对像)
        private static string _reocrdValue = "";

        public static string ReocrdValue
        {
            get { return MYWebServer._reocrdValue; }
            set { MYWebServer._reocrdValue = value; }
        }
        #endregion 

        #region 存放 系统中的临时用户
        //public static List<UserEntity> userList = new List<UserEntity>();
        public static List<object> userList = new List<object>();
        #endregion

        #region 连接打开的html页面
        //recordValue
        public static string reocrdLive = "";
        //error.htm
        public static string error = "";
        //login.htm
        public static string login = "";
        //login.htm
        public static string login1 = "";
        #endregion 

        /
        STWebServer webServer;

        /// <summary>
        /// 初始化网络服务 显示不同网页的基本内容
        /// </summary>
        /// <param name="ip">系统IP</param>
        /// <param name="port">网络端口</param>
        /// <param name="SB_ip">设备ip</param>
        /// <param name="SB_port">设备端口</param>
        /// <param name="SB_userName">设备用户</param>
        /// <param name="SB_passWord">设备密码</param>
        /// <param name="CrRoomid">视频直播的对讲房间Id</param>
        /// <param name="WBBoardID"></param>
        public void init(string ip,string port
            ,string SB_ip,string SB_port,string SB_userName,string SB_passWord,
            string CrRoomid, string WBBoardID,string sttype)
        {
            try
            {
                string reocrdLive1 ="";
                //switch (sttype)
                //{
                //    case APP.AppProperty.SB_StrNEWS600:
                reocrdLive1 = "";                                          //Application.StartupPath + "\\reocrdLive\\reocrdLive1.htm";
                //        break;
                //    default:
                //        reocrdLive1 = Application.StartupPath + "\\reocrdLive\\reocrdLive.htm";
                //        break;
                //}
                
                string text = File.ReadAllText(reocrdLive1, Encoding.Default);
                //
                text = text.Replace("@url", "http://" + ip + ":" + port + "/bl");
                text = text.Replace("@serverIp", ip);//"192.168.1.57"
                text = text.Replace("@fdblive_ip", SB_ip);//"192.168.1.163"
                text = text.Replace("@fdblive_port", SB_port);//"3000"
                text = text.Replace("@fdblive_name", SB_userName);//"888888"
                text = text.Replace("@fdblive_pwd", SB_passWord);//"888888"
                text = text.Replace("@fdblive_roomId", CrRoomid);//"10500"
                text = text.Replace("@WBBoard_roomId", "6BF52A52-394A-11d3-B153-00C04F79FAA6");

                MYWebServer.reocrdLive = text;

                string error = "";// Application.StartupPath + "\\reocrdLive\\error.htm";
                string errortext = File.ReadAllText(error, Encoding.Default);
                MYWebServer.error = errortext;

                string login = "";//Application.StartupPath + "\\reocrdLive\\login.htm";
                string logintext = File.ReadAllText(login, Encoding.Default);
                logintext = logintext.Replace("@loginurl", "http://" + ip + ":" + port + "/zb");//"888888"
                MYWebServer.login = logintext;

                string login1 = "";//Application.StartupPath + "\\reocrdLive\\login1.htm";
                string login1text = File.ReadAllText(login1, Encoding.Default);
                login1text = login1text.Replace("@loginurl", "http://" + ip + ":" + port + "/zb");//"888888"
                MYWebServer.login1 = login1text;
            }
            catch (Exception ex)
            {
                //APP.Loger.Writer(ex, "初始化网络直播服务");
            }
            
        }

        //启动
        public void StartWebServer(string ip="", string port="80")
        {
            try
            {
                //启动httpServer  应该是进入笔录系统后再启动
                STWebServer.port = int.Parse(port);
                webServer = new STWebServer();
            }
            catch (Exception ex)
            {
                //APP.Loger.Writer(ex, "启动网络直播服务");
            }
            
        }
        //关闭
        public void StopWebServer()
        {
            try
            {
                webServer.DisposeServer();
            }
            catch (Exception ex)
            {
                //APP.Loger.Writer(ex, "关闭网络直播服务");
            }
        }
        //重启httpserver
        public void NeadREStartWebServer(string ip = "", string port = "")
        {
            try
            {
                webServer.DisposeServer();
                STWebServer.port = int.Parse(port);
                webServer = new STWebServer();
            }
            catch (Exception ex)
            {
                //APP.Loger.Writer(ex, "重启网络直播服务");
            }
            
        }
    }
    internal class HttpRequest
    {
        private System.Collections.Hashtable paramsKeyMap;

        public System.Collections.Hashtable ParamsKeyMap
        {
            get { return paramsKeyMap; }
            set { paramsKeyMap = value; }
        }
        public void parseParamsMap(string url)
        {
            string[] ccc = url.Split('?');
            if (ccc.Length == 2)
            {
                string _strparams = ccc[1];
                string[] key = _strparams.Split('&');
                ParamsKeyMap = new System.Collections.Hashtable(key.Length);
                foreach (string k in key)
                {
                    string[] ky = k.Split('=');
                    if (ky.Length == 2)
                    {
                        paramsKeyMap.Add(ky[0], ky[1]);
                    }
                    else if (ky.Length == 1)
                    {
                        paramsKeyMap.Add(ky[0], "");
                    }
                }
            }
        }
        public string this[string key]
        {
            get
            {
                if (ParamsKeyMap != null)
                {
                    if (ParamsKeyMap.ContainsKey(key))
                    {
                        return (string)ParamsKeyMap[key];
                    }
                    else
                    {
                        return "";
                    }
                }
                else
                {
                    return "";
                }
            }

        }


    }
    internal class SocketParams
    {
        private System.Net.Sockets.Socket m_accpetSocket = null;
        private System.Threading.Thread m_curThread = null;
        private STWebServer m_ptrWebServer = null;
        public SocketParams(ref System.Net.Sockets.Socket target)
        {
            this.m_accpetSocket = target;
        }
        public void set_WebServerPtr(STWebServer ptr)
        {
            this.m_ptrWebServer = ptr;
        }
        public void set_thread(ref System.Threading.Thread pthread)
        {
            this.m_curThread = pthread;
        }
        public void SendHeader(string sHttpVersion, string sMIMEHeader, int iTotBytes, string sStatusCode, ref Socket mySocket)
        {
            String sBuffer = "";

            if (sMIMEHeader.Length == 0)
            {
                sMIMEHeader = "text/html"; // 默认 text/html
            }
            //
            sBuffer = sBuffer + sHttpVersion + " " + sStatusCode + "\r\n";
            sBuffer = sBuffer + "Server: cx1193719-b\r\n";
            sBuffer = sBuffer + "Content-Type: " + sMIMEHeader + "\r\n";
            sBuffer = sBuffer + "Accept-Ranges: bytes\r\n";
            sBuffer = sBuffer + "Content-Length: " + iTotBytes + "\r\n\r\n";


            Byte[] bSendData = Encoding.ASCII.GetBytes(sBuffer);

            SendToBrowser(bSendData, ref mySocket);

            Console.WriteLine("Total Bytes : " + iTotBytes.ToString());


            //String sBuffer = "";

            //if (sMIMEHeader.Length == 0)
            //{
            //    sMIMEHeader = "text/html"; // 默认 text/html
            //}

            //sBuffer = sBuffer + sHttpVersion + sStatusCode + "\r\n";
            //sBuffer = sBuffer + "Server: cx1193719-b\r\n";
            //sBuffer = sBuffer + "Content-Type: " + sMIMEHeader + "\r\n";
            //sBuffer = sBuffer + "Accept-Ranges: bytes\r\n";
            //sBuffer = sBuffer + "Content-Length: " + iTotBytes + "\r\n\r\n";

            //Byte[] bSendData = Encoding.ASCII.GetBytes(sBuffer);

            //SendToBrowser(bSendData, ref mySocket);

            //Console.WriteLine("Total Bytes : " + iTotBytes.ToString());
        }
        private object lockHelper = new object();
        private const string xml = "<?xml version=\"1.0\" encoding=\"gb2312\" ?><Record-status>{0}</Record-status>";
        public System.Collections.Hashtable parseParamMap(string _param)
        {
            string[] arr = _param.Split('&');
            string[] av;
            System.Collections.Hashtable _requestParams = new System.Collections.Hashtable();
            foreach (string o in arr)
            {
                av = o.Split('=');
                if (av.Length == 2)
                {
                    _requestParams.Add(av[0], av[1]);
                }
            }
            return _requestParams;
        }

        public string getIP(string str)
        {
            string[] arr = str.Split(':');
            if (arr.Length == 2)
            {
                return arr[0];
            }
            else
            {
                return str;
            }
        }
        public int min(int f, int l)
        {
            if (f > l)
            {
                return l;
            }
            else
            {
                return f;
            }
        }
        public void SendToBrowser(String sData, ref Socket mySocket)
        {
            SendToBrowser(Encoding.ASCII.GetBytes(sData), ref mySocket);
        }
        int NET_MTU = 1500;
        public void SendToBrowser(Byte[] bSendData, ref Socket mySocket)//23155
        {
            int numBytes = 0;

            try
            {
                if (mySocket.Connected)
                {
                    int totallen = bSendData.Length;
                    int curr_pos = 0;
                    if (totallen <= NET_MTU)
                    {
                        if ((numBytes = mySocket.Send(bSendData, totallen, 0)) != -1)
                        {

                        }
                    }
                    else
                    {
                        int left_size = NET_MTU;
                        int send_len = 0;
                        while ((numBytes = mySocket.Send(bSendData, curr_pos, left_size, 0)) != -1)
                        {
                            curr_pos += left_size;
                            send_len += numBytes;
                            left_size = totallen - send_len;
                            if (left_size >= NET_MTU)
                            {
                                left_size = NET_MTU;
                            }
                            if (left_size == 0)
                            {
                                break;
                            }
                        }
                        Console.WriteLine("###Send Total Size:" + send_len);
                    }
                }
                else
                    Console.WriteLine("连接失败....");
            }
            catch (Exception e)
            {
                Console.WriteLine("发生错误 : {0} ", e);
                //APP.Loger.Writer(e, "SendToBrowser");
            }
        }
        public void ServiceRecv()
        {
            try
            {
                do
                {
                    if (null == m_accpetSocket) break;
                    if (m_accpetSocket.Connected)
                    {
                        int iStartPos = 0;
                        String sRequest;
                        String sDirName;
                        //String sRequestedFile;
                        String sErrorMessage;
                        int returnStatus = -1;

                        Byte[] bReceive = new Byte[1024 * 4];
                        try
                        {
                            int i = m_accpetSocket.Receive(bReceive, bReceive.Length, 0);
                        }
                        catch (System.Exception e)
                        {
                            //APP.Loger.Writer(e, "");
                            m_accpetSocket.Close();
                            continue;
                        }

                        HttpRequest request = new HttpRequest();
                        string icc = "";
                        string hostIp = "";
                        string sHttpVersion = "";
                        try
                        {
                            string sBuffer = Encoding.ASCII.GetString(bReceive);

                            //只处理"get"请求类型
                            if (sBuffer.Substring(0, 3) != "GET")
                            {
                                Console.WriteLine("只处理get请求类型..");
                                m_accpetSocket.Close();
                                continue;
                            }

                            // 查找 "HTTP" 的位置
                            iStartPos = sBuffer.IndexOf("HTTP", 1);

                            sHttpVersion = sBuffer.Substring(iStartPos, 8);


                            // 得到请求类型和文件目录文件名
                            sRequest = sBuffer.Substring(0, iStartPos - 1);

                            sRequest.Replace("\\", "/");


                            //如果结尾不是文件名也不是以"/"结尾则加"/"
                            if ((sRequest.IndexOf(".") < 1) && (!sRequest.EndsWith("/")))
                            {
                                sRequest = sRequest + "/";
                            }

                            //判断参数
                            string[] arr = sRequest.Split('?');


                            //得到请求文件目录 "GET /loginaAction.cgi?txtUsername=admin&txtPassword=admin"
                            sDirName = sRequest.Substring(sRequest.IndexOf("/"), sRequest.LastIndexOf("/") - 3);

                            int len = sRequest.IndexOf("/");
                            icc = sRequest.Substring(len, sRequest.Length - len);

                            request.parseParamsMap(icc);
                            //取出IP
                            try
                            {
                                Console.WriteLine("\nClient Connected!!\n==================\nCLient IP {0}\n", m_accpetSocket.RemoteEndPoint);
                                hostIp = getIP(m_accpetSocket.RemoteEndPoint.ToString());
                            }
                            catch (System.Exception e)
                            {
                                //APP.Loger.Writer(e, "");
                            }
                        }
                        catch (Exception ex) { //APP.Loger.Writer(ex, "");
                        }


                        try
                        {
                            //http://localhost:8110/zb  //  浏览器中输入的url,获取整个页面
                            //http://localhost:8110/bl  //  网页定时获取笔录
                            //main.jpg //  网页logo
                            //login.jpg // 登陆Logo
                            //PNG图像 .jpg image/png   
                            //GIF图形 .gif image/gif   
                            //JPEG图形 .jpeg,.jpg image/jpeg 
                            //rar application/x-rar-compressed 
                            //exe application/octet-stream

                            icc = icc.ToLower();
                            //登陆 
                            if (icc.IndexOf("/dl") != -1)
                            {
                                sErrorMessage = LoginWebForm(hostIp, sHttpVersion);
                            }
                            else if (icc.IndexOf("/zb") != -1)
                            {
                                lock (lockHelper)
                                {
                                    string[] arryParam = icc.Split('&');


                                    //默认以指挥人员身份登录;0:指挥人员,1:受令人员
                                    string loginType = "0";
                                    if (arryParam.Length == 5)
                                    {
                                        loginType = arryParam[3].Replace("login=", "").Replace("/", ""); ;
                                    }
                                    else if (arryParam.Length <= 3)
                                    {
                                        return;
                                    }

                                    string userName = arryParam[1];
                                    string password = arryParam[2].Replace("/", "");

                                    //得到参数后,判断是否是加密过后的
                                    string passwordType = arryParam[4];
                                    sErrorMessage = WebForm3(sHttpVersion, ref loginType, userName, password, passwordType);

                                }
                            }
                            else if (icc.IndexOf("/bl") != -1)
                            {
                                lock (lockHelper)
                                {
                                    MYWebServer.ReocrdValue = MYWebServer.ReocrdValue.Replace("\n","<br>");
                                    //这里取笔录
                                    sErrorMessage = MYWebServer.ReocrdValue;
                                    SendHeader(sHttpVersion, "text/html", Encoding.UTF8.GetBytes(sErrorMessage).Length, "200 OK", ref m_accpetSocket);
                                    SendToBrowser(Encoding.UTF8.GetBytes(sErrorMessage), ref m_accpetSocket);

                                    Console.WriteLine("Web Server Running... RECORD");
                                }
                            }
                            else if (icc.Equals("/reocrdlive/img/login.jpg"))
                            {
                                lock (lockHelper)
                                {
                                    //这里取loginlogo
                                    string loginLogo = "";//Application.StartupPath + "\\reocrdLive\\img\\login.jpg";
                                    m_accpetSocket.SendFile(loginLogo);

                                }
                            }
                            else if (icc.Equals("/reocrdlive/img/main.jpg"))
                            {
                                lock (lockHelper)
                                {
                                    //这里取mainlogo
                                    string mainLogo = "";// Application.StartupPath + "\\reocrdLive\\img\\main.jpg";
                                    m_accpetSocket.SendFile(mainLogo);

                                }
                            }
                            else if (icc.IndexOf("/reocrdlive/tools/bord.exe") != -1)
                            {
                                lock (lockHelper)
                                {
                                    //这里取mainlogo
                                    string bordFile = "";//Application.StartupPath + "\\reocrdLive\\tools\\bord.exe";
                                    if (File.Exists(bordFile))
                                    {
                                        m_accpetSocket.SendFile(bordFile);
                                    }
                                }
                            }
                            else if (icc.IndexOf("/reocrdlive/tools/laviview.exe") != -1)
                            {
                                lock (lockHelper)
                                {
                                    //这里取mainlogo
                                    string laviViewFile = "";//Application.StartupPath + "\\reocrdLive\\tools\\LaviView.exe";
                                    m_accpetSocket.SendFile(laviViewFile);
                                }
                            }
                            else if (icc.IndexOf("/reocrdlive/tools/axaudiotalk.exe") != -1)
                            {
                                lock (lockHelper)
                                {
                                    //这里取mainlogo
                                    string laviViewFile = "";// Application.StartupPath + "\\reocrdLive\\tools\\AxAudioTalk.exe";
                                    m_accpetSocket.SendFile(laviViewFile);
                                }
                            }
                            else
                            {
                                //sErrorMessage = string.Format(xml, returnStatus);
                                //SendHeader(sHttpVersion, "", sErrorMessage.Length, " 200 OK", ref m_accpetSocket);
                                //SendToBrowser(sErrorMessage, ref m_accpetSocket);
                            }
                        }
                        catch (Exception ex)
                        {
                            //APP.Loger.Writer(ex, "");
                            sErrorMessage = string.Format(xml, returnStatus);
                            SendHeader(sHttpVersion, "", sErrorMessage.Length, " 200 OK", ref m_accpetSocket);
                            SendToBrowser(sErrorMessage, ref m_accpetSocket);
                        }
                        try
                        {
                            m_accpetSocket.Close();
                        }
                        catch
                        {

                        }
                    }
                } while (false);
            }
            catch (Exception ex)
            {
                //APP.Loger.Writer(ex, "");
            }

            if (null != m_curThread && null != m_ptrWebServer)
            {
                m_ptrWebServer.remove_thread(ref m_curThread);
            }
        }

        private String WebForm3(string sHttpVersion, ref string loginType, string userName, string password, string passwordType)
        {
            String sErrorMessage="";
            if (passwordType.Equals("passwordtype=0/"))
            {
                sErrorMessage = webForm1(sHttpVersion, ref loginType, userName, password);
            }
            else if (passwordType.Equals("passwordtype=1/"))
            {
                //foreach (UserEntity ue in MYWebServer.userList)
                //{
                //    string pasw=EncryptArithmetic.Encode(ue.STPassWord).ToLower();
                //    string pasw1 = EncryptArithmetic.Encode(password).ToLower();
                //    if (ue.STUserName.Equals(userName) && pasw.Equals(pasw1))
                //    {
                //        string roleType = "受令";
                //        if (!ue.QuanXianJueSe.Equals("指挥"))
                //        {
                //            //自动切换为受令人员;
                //            loginType = "1";
                //            roleType = "受令";
                //        }

                //        if (loginType.Equals("0"))
                //        {
                //            roleType = "指挥";
                //        }
                //        else
                //        {
                //            roleType = "受令";
                //        }
                //        //跳转到加密界面
                //        //这里取登陆界面
                //        sErrorMessage = MYWebServer.login1.Replace("@userName", userName).Replace("@Password", EncryptArithmetic.Encode(password).ToLower()).Replace("@login", loginType);

                //        SendHeader(sHttpVersion, "text/html", Encoding.Default.GetBytes(sErrorMessage).Length, "200 OK", ref m_accpetSocket);//22510

                //        SendToBrowser(Encoding.Default.GetBytes(sErrorMessage), ref m_accpetSocket);
                //        break;
                //    }
                //}
            }
            return sErrorMessage;
        }

        private String webForm1(string sHttpVersion, ref string loginType, string userName, string password)
        {
            String sErrorMessage="";
            //hostIp
            //foreach (UserEntity ue in MYWebServer.userList)
            //{
            //    string pasw = EncryptArithmetic.Encode(ue.STPassWord).ToLower();
            //    if (ue.STUserName.Equals(userName) && pasw.Equals(password))
            //    {
            //        string roleType = "受令";
            //        if (!ue.QuanXianJueSe.Equals("指挥"))
            //        {
            //            //自动切换为受令人员;
            //            loginType = "1";
            //            roleType = "受令";
            //        }
            //        if (loginType.Equals("0"))
            //        {
            //            roleType = "指挥";
            //        }
            //        else
            //        {
            //            roleType = "受令人员";
            //        }
            //        string newHTML = MYWebServer.reocrdLive.Replace("@userName", ue.STUserName).Replace("@recv_talk", loginType).Replace("@loginType", roleType);
            //        //PublicForm.reocrdLive;
            //        //这里取直播界面
            //        //sErrorMessage = PublicForm.reocrdLive;//.Replace("@txt_userName", "").Replace("@txt_userName", "");
            //        SendHeader(sHttpVersion, "text/html", Encoding.Default.GetBytes(newHTML).Length, "200 OK", ref m_accpetSocket);//22510
            //        SendToBrowser(Encoding.Default.GetBytes(newHTML), ref m_accpetSocket);
            //        break;
            //    }
            //}
            //这里取直播界面
            sErrorMessage = MYWebServer.error;

            SendHeader(sHttpVersion, "text/html", Encoding.Default.GetBytes(sErrorMessage).Length, "200 OK", ref m_accpetSocket);//22510

            SendToBrowser(Encoding.Default.GetBytes(sErrorMessage), ref m_accpetSocket);
            return sErrorMessage;
        }

        private String LoginWebForm(string hostIp, string sHttpVersion)
        {
            String sErrorMessage="";
            lock (lockHelper)
            {
                ////hostIp
                //foreach (UserEntity ue in MYWebServer.userList)
                //{
                //    if (ue.BangDingIP!=null&&ue.BangDingIP.Equals(hostIp))
                //    {
                //        //这里取登陆界面
                //        sErrorMessage = MYWebServer.login.Replace("@txt_userName", ue.STUserName).Replace("@txt_password", ue.STPassWord);
                //        SendHeader(sHttpVersion, "text/html", Encoding.Default.GetBytes(sErrorMessage).Length, "200 OK", ref m_accpetSocket);//22510
                //        SendToBrowser(Encoding.Default.GetBytes(sErrorMessage), ref m_accpetSocket);
                //        break;
                //    }
                //}
                ////这里空登陆界面
                //sErrorMessage = MYWebServer.login.Replace("@txt_userName", "").Replace("@txt_password", "");

                //SendHeader(sHttpVersion, "text/html", Encoding.Default.GetBytes(sErrorMessage).Length, "200 OK", ref m_accpetSocket);//22510

                //SendToBrowser(Encoding.Default.GetBytes(sErrorMessage), ref m_accpetSocket);

            }
            return sErrorMessage;
        }
    }
    internal class STWebServer : IDisposable
    {
        private const string xml = "<?xml version=\"1.0\" encoding=\"gb2312\" ?><Record-status>{0}</Record-status>";

        private TcpListener myListener;
        public static int port = 80; // 选者任何闲置端口
        public static System.Collections.Hashtable ipMap = new System.Collections.Hashtable();

        private Thread th;

        //开始兼听端口   同时启动一个兼听进程
        public STWebServer()
        {
            try
            {
                //开始兼听端口
                myListener = new TcpListener(port);
                myListener.Start();
                Console.WriteLine("Web Server Running... Press ^C to Stop...");
                //同时启动一个兼听进程 ''StartListen''
                th = new Thread(new ThreadStart(StartListen));
                th.Start();
            }
            catch (Exception e)
            {
                Console.WriteLine("兼听端口时发生错误 :" + e.ToString());
            }
        }

        ~STWebServer()
        {
            if (th != null)
            {
                th.Abort();
            }
            //t.Stop();
        }
        public delegate void update(string word);
        System.Windows.Forms.ListBox _listBox;
        System.Windows.Forms.Label _label;
        public void SetListBox(ref System.Windows.Forms.Label _label)
        {
            this._label = _label;

        }
        public void ShowMessage(string mes)
        {
            //_label.Text = mes;
            //System.Windows.Forms.MessageBox.Show(mes);
        }
        public void SetListBox(ref System.Windows.Forms.ListBox _listBox)
        {
            this._listBox = _listBox;

        }
        public void _removeList(string word)
        {
            if (_listBox.Items.Contains(word))
            {
                int index = 0;
                foreach (string str in _listBox.Items)
                {
                    if (str.Equals(word))
                    {
                        _listBox.Items.RemoveAt(index);
                        break;
                    }
                    index++;
                }
                //_listBox.Items.Remove(word);
            }
        }
        public void _updateList(string word)
        {
            int len = _listBox.Items.Count;
            if (len == 0)
            {
                _listBox.Items.Add(word);
            }
            else
            {
                if (_listBox.Items.Contains(word))
                {
                    int index = 0;
                    foreach (string str in _listBox.Items)
                    {
                        if (str.Equals(word))
                        {
                            _listBox.Items.RemoveAt(index);
                            break;
                        }
                        index++;
                    }
                    //_listBox.Items.Remove(word);
                }
                else
                {
                    _listBox.Items.Add(word);
                }
            }
        }

        public void listShow(string word)
        {
            this._listBox.BeginInvoke(new update(_updateList), word);
        }
        public void removeList(string word)
        {
            this._listBox.BeginInvoke(new update(_removeList), word);
        }

        public void SendHeader(string sHttpVersion, string sMIMEHeader, int iTotBytes, string sStatusCode, ref Socket mySocket)
        {
            String sBuffer = "";

            if (sMIMEHeader.Length == 0)
            {
                sMIMEHeader = "text/html"; // 默认 text/html
            }

            sBuffer = sBuffer + sHttpVersion + sStatusCode + "\r\n";
            sBuffer = sBuffer + "Server: cx1193719-b\r\n";
            sBuffer = sBuffer + "Content-Type: " + sMIMEHeader + "\r\n";
            sBuffer = sBuffer + "Accept-Ranges: bytes\r\n";
            sBuffer = sBuffer + "Content-Length: " + iTotBytes + "\r\n\r\n";


            Byte[] bSendData = Encoding.ASCII.GetBytes(sBuffer);

            SendToBrowser(bSendData, ref mySocket);

            Console.WriteLine("Total Bytes : " + iTotBytes.ToString());


            //String sBuffer = "";

            //if (sMIMEHeader.Length == 0)
            //{
            //    sMIMEHeader = "text/html"; // 默认 text/html
            //}

            //sBuffer = sBuffer + sHttpVersion + sStatusCode + "\r\n";
            //sBuffer = sBuffer + "Server: cx1193719-b\r\n";
            //sBuffer = sBuffer + "Content-Type: " + sMIMEHeader + "\r\n";
            //sBuffer = sBuffer + "Accept-Ranges: bytes\r\n";
            //sBuffer = sBuffer + "Content-Length: " + iTotBytes + "\r\n\r\n";

            //Byte[] bSendData = Encoding.ASCII.GetBytes(sBuffer);

            //SendToBrowser(bSendData, ref mySocket);

            //Console.WriteLine("Total Bytes : " + iTotBytes.ToString());
        }
        private object lockHelper = new object();
        public void SendToBrowser(String sData, ref Socket mySocket)
        {
            SendToBrowser(Encoding.ASCII.GetBytes(sData), ref mySocket);
        }
        int NET_MTU = 1500;
        public void SendToBrowser(Byte[] bSendData, ref Socket mySocket)//23155
        {
            int numBytes = 0;

            try
            {
                if (mySocket.Connected)
                {
                    int totallen = bSendData.Length;
                    int curr_pos = 0;
                    if (totallen <= NET_MTU)
                    {
                        if ((numBytes = mySocket.Send(bSendData, totallen, 0)) != -1)
                        {

                        }
                    }
                    else
                    {
                        int left_size = NET_MTU;
                        int send_len = 0;
                        while ((numBytes = mySocket.Send(bSendData, curr_pos, left_size, 0)) != -1)
                        {
                            curr_pos += left_size;
                            send_len += numBytes;
                            left_size = totallen - send_len;
                            if (left_size >= NET_MTU)
                            {
                                left_size = NET_MTU;
                            }
                            if (left_size == 0)
                            {
                                break;
                            }
                        }
                        Console.WriteLine("###Send Total Size:" + send_len);
                    }


                }
                else
                    Console.WriteLine("连接失败....");
            }
            catch (Exception e)
            {
                Console.WriteLine("发生错误 : {0} ", e);

            }
        }

        public System.Collections.Hashtable parseParamMap(string _param)
        {
            string[] arr = _param.Split('&');
            string[] av;
            System.Collections.Hashtable _requestParams = new System.Collections.Hashtable();
            foreach (string o in arr)
            {
                av = o.Split('=');
                if (av.Length == 2)
                {
                    _requestParams.Add(av[0], av[1]);
                }
            }
            return _requestParams;
        }

        public string getIP(string str)
        {
            string[] arr = str.Split(':');
            if (arr.Length == 2)
            {
                return arr[0];
            }
            else
            {
                return str;
            }
        }
        public int min(int f, int l)
        {
            if (f > l)
            {
                return l;
            }
            else
            {
                return f;
            }
        }
        private List<Thread> ThList = null;
        public void remove_thread(ref Thread traget)
        {
            try
            {
                if (null != ThList)
                {
                    if (ThList.Contains(traget))
                    {
                        ThList.Remove(traget);
                    }

                    //traget.Abort();
                }
            }
            catch (Exception ex)
            {
                //APP.Loger.Writer(ex, "");
                //Console.WriteLine(ex.Message);
            }
        }
        public void StartListen()
        {
            int iStartPos = 0;
            String sRequest;
            String sDirName;
            //String sRequestedFile;
            String sErrorMessage;


            while (true)
            {
                //接受新连接
                lock (lockHelper)
                {
                    Socket mySocket = myListener.AcceptSocket();
                    SocketParams param = new SocketParams(ref mySocket);
                    Thread T = new Thread(new ThreadStart(param.ServiceRecv));
                    param.set_thread(ref T);
                    param.set_WebServerPtr(this);
                    T.Start();
                    if (ThList == null)
                    {
                        ThList = new List<Thread>();
                    }
                    ThList.Add(T);
                }
            }
        }

        public void DisposeServer()
        {
            try
            {
                //ViewManager.Instance.clear();
                ipMap.Clear();
                th.Abort();
                myListener.Stop();
            }
            catch { }
        }

        #region IDisposable 成员

        void IDisposable.Dispose()
        {
            try
            {
                DisposeServer();
            }
            catch { }
        }

        #endregion
    }
}

 

转载于:https://www.cnblogs.com/longkai178/p/5815202.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值