为什么不回答我的Windows服务? [英] why no answer my Windows Services?

查看:60
本文介绍了为什么不回答我的Windows服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hi
这个项目使用Windows服务用来连接客户端。

但是当我安装&运行服务,什么都不做。



windows服务

套接字编程(套接字服务器)



我的代码项目是:



hi This project uses the Windows service uses to connect to the client.
But i when the install & run service, that are not doing nothing.

windows service
socket programing (socket server)

my code project is:

//static main
 static void Main()
        {
            db_connection ob_db = new db_connection();
            ob_db.get_ip_port();
            activator_service_01.activator_srv_Service.ip_srv = activator_service_01.db_connection.ip_srv_db;
            activator_service_01.activator_srv_Service.port_srv = activator_service_01.db_connection.port_srv_db;

            System.ServiceProcess.ServiceBase[] ServicesToRun;
            // Change the following line to match.
            ServicesToRun = new System.ServiceProcess.ServiceBase[] 
            { 
                new activator_srv_Service()
            };
            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
        }

//-------------------*******************-------------------
//-------------------*******************-------------------
    partial class activator_srv_Service : System.ServiceProcess.ServiceBase
    {
        public static string ip_srv;
        public static int port_srv; 
       
        private static string res_req_client;
        Thread srv_t;

        public activator_srv_Service()
        {
            InitializeComponent();
            
            this.AutoLog = true;

            if (!System.Diagnostics.EventLog.SourceExists("MySource"))
            {
                System.Diagnostics.EventLog.CreateEventSource(
                   "MySource", "MyNewLog");
            }
            eventLog_ActivatorService.Source = "MySource";
            eventLog_ActivatorService.Log = "MyNewLog";

        } //سازنده کلاس

        protected override void OnStart(string[] args)
        {

            start_socket();
            eventLog_ActivatorService.WriteEntry("In OnStart");
            // TODO: Add code here to start your service.
        }

        protected override void OnStop()
        {
            eventLog_ActivatorService.WriteEntry("In onStop.");
            srv_t.Abort();
            // TODO: Add code here to perform any tear-down necessary to stop your service.
        }
        protected override void OnContinue()
        {
           
            eventLog_ActivatorService.WriteEntry("In OnContinue.");
        }

        void start_socket()
        {
            try
            {
                srv_t = new Thread(new ThreadStart
                    (activator_srv_Service.AsynchronousSocketListener.StartListening));
                srv_t.IsBackground = true;
                srv_t.Start();
                
                return;
            }
            catch
            {
                return;
            }
        } 

        public class StateObject  
        {

            public Socket workSocket = null; 
            public const int BufferSize = 1024; 
            public byte[] buffer = new byte[BufferSize];  
            public StringBuilder sb = new StringBuilder(); 

        } //end public class StateObject
        public class AsynchronousSocketListener
        {

            public static ManualResetEvent allDone = new ManualResetEvent(false);

            public AsynchronousSocketListener()
            {
            }

            public static string check_user_reg_fetch(string client_str) 
            {
                
                string[] tmp_client_info = client_str.Split('#');

                string active_code = tmp_client_info[0];
                active_code = active_code.Replace("'", "''");
                active_code = active_code.Trim();

                string ip_client = tmp_client_info[1];
                ip_client = ip_client.Replace("'", "''");
                ip_client = ip_client.Trim();

                string port_client = tmp_client_info[2];
                port_client = port_client.Replace("'", "''");
                port_client = port_client.Trim();

                string con_str_client = tmp_client_info[3];
                con_str_client = con_str_client.Replace("'", "''");
                con_str_client = con_str_client.Trim();

                db_connection ob_db = new db_connection();
                string sub_active_code = active_code.Substring(0, 5);

                string query_check;

                if (sub_active_code == "IR04R")
                {
                    query_check = "SELECT active_code_r FROM tbl_srv_1 WHERE active_code_r= '" + active_code + "' ";
                    ob_db.check_active_code(query_check, sub_active_code, ip_client, port_client, con_str_client);

                    res_req_client = ob_db.result_req_client;
                }
                else if (sub_active_code == "IR04M")
                {
                    query_check = "SELECT active_code_m FROM tbl_srv_2 WHERE active_code_m= '" + active_code + "' ";
                    ob_db.check_active_code(query_check, sub_active_code, ip_client, port_client, con_str_client);

                    res_req_client = ob_db.result_req_client;

                }
                else if (sub_active_code == "IR04S")
                {
                    query_check = "SELECT active_code_s FROM tbl_srv_3 WHERE active_code_s= '" + active_code + "' ";
                    ob_db.check_active_code(query_check, sub_active_code, ip_client, port_client, con_str_client);

                    res_req_client = ob_db.result_req_client;
                }
                else if (sub_active_code == "IR04C")
                {
                    query_check = "SELECT active_code_c FROM tbl_4 WHERE active_code_c= '" + active_code + "' ";
                    ob_db.check_active_code(query_check, sub_active_code, ip_client, port_client, con_str_client);

                    res_req_client = ob_db.result_req_client;
                }
                return res_req_client;
                //} //end if "Data to the remote device."
            }

            public static void StartListening()
            { 
                byte[] recvDataBytes = new byte[1024]; 

                //IPAddress serverAdd = Dns.Resolve("localhost"); 
                IPHostEntry ipHost = Dns.Resolve(ip_srv);
                IPAddress serverAdd = ipHost.AddressList[0];
                IPEndPoint ep = new IPEndPoint(serverAdd, port_srv);

                Socket listenerSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    listenerSock.Bind(ep); 
                    listenerSock.Listen(10);

                    while (true)
                    {
                        allDone.Reset(); 
                        //Console.WriteLine("wating for client..."); 
                       listenerSock.BeginAccept(new AsyncCallback(AcceptCallback), listenerSock);
                        allDone.WaitOne(); 
                    }
                }
                catch //(Exception e)
                {
                    //MessageBox.Show(e.ToString(), "erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                //Console.WriteLine("\nperss Enter to continue...");
                //Console.Read();
            } // end public static void StartListening

            public static void AcceptCallback(IAsyncResult ar)
            {
                allDone.Set();

                Socket listener = (Socket)ar.AsyncState;
                Socket handler = listener.EndAccept(ar);

                StateObject state = new StateObject(); 
                state.workSocket = handler;
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);

            } // end public static void AcceptCallback
            public static void ReadCallback(IAsyncResult ar)
            {
                string content = string.Empty;
                StateObject state = (StateObject)ar.AsyncState;// Retrieve the state object and the handler socket
                Socket handler = state.workSocket; // from the asynchronous state object.
                int bytesRead = handler.EndReceive(ar); 
                if (bytesRead > 0)
                {
                    //state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead)); 
                    state.sb.Append(System.Text.UTF8Encoding.UTF8.GetString(state.buffer, 0, bytesRead));// There might be more data, so store the data received so far.


                   
                    content = state.sb.ToString();

                    if (content == "" || content == "Data to the remote device.")
                    {
                        content = "Hi, I'm wating for your request...";
                    }
                    else
                    {

                        content = check_user_reg_fetch(content);

                    }
                    //    Console.WriteLine(content);

                    //}
                    //catch (Exception e)
                    //{

                    //    MessageBox.Show(e.ToString(), "erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //}   

                    if (content.IndexOf("") > -1)
                    {
                        
                        //Console.WriteLine("Read {0} bytes from socket. \n Data: {1}", content.Length, content);
                        Send(handler, content); 
                    }  //end if(content.IndexOf("")>-1)
                    else
                    {
                        
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                    }

                } // end (bytesRead > 0)

            } // end public static void ReadCallback

            private static void Send(Socket handler, string data)
            {
                //byte[] byteDate = Encoding.ASCII.GetBytes(data); 
                byte[] byteData = System.Text.UTF8Encoding.UTF8.GetBytes(data); 
                handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);

            } // end private static void Send

            private static void SendCallback(IAsyncResult ar)
            {
                try
                {
                    Socket handler = (Socket)ar.AsyncState;  
                    int byteSent = handler.EndSend(ar);
                    //Console.WriteLine("Sent {0} bytes to client.", byteSent);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
                catch (Exception e)
                {
                    //MessageBox.Show(e.ToString(),"error" ,MessageBoxButtons.OK,MessageBoxIcon.Error);
                    //Console.WriteLine(e.ToString());
                }

            } // end private static void SendCallback


        } //end public class AsynchronousSocketListener

    
    }
}

//-------------------*******************-------------------
//-------------------*******************-------------------
//*********************************************
// and my Data base Class code is:
//*********************************************
 class db_connection
    {
        public static string[] pool_info;

        SqlConnection con;
        SqlCommand cmd;

        public string result_req_client;
        
        public static string ip_srv_db;
        public static int port_srv_db;
        
        public static string strCon_sysDb = (@"Data Source=.;Initial Catalog=_ServerDb;Integrated Security=True");
        private void con_db()
        {
            con = new SqlConnection(strCon_sysDb);
            con.Open();

        }

        protected void del_update_insert(string query)
        {
            con_db();
            cmd = new SqlCommand(query, con);
            cmd.ExecuteNonQuery();

            con.Close();
            SqlConnection.ClearPool(con);

        }

        public void get_ip_port() 
        {
            con_db();
            string query = "SELECT ip_set , port_set FROM tbl_set_service WHERE srv_call = 'activator_srv'";

            cmd = new SqlCommand(query, con);
            SqlDataReader dr;

            dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                ip_srv_db = (dr["ip_set"].ToString()).Trim();
                port_srv_db =Convert.ToInt32((dr["port_set"].ToString()).Trim());
            }
            else {
               
                ip_srv_db = "127.0.0.1";
                port_srv_db =6363 ;
            }
            dr.Close();

            con.Close();
            SqlConnection.ClearPool(con);

        }//end public void get_ip_port

        protected void get_req(string query, string check_db)
        {  // fetch

            con_db();

            cmd = new SqlCommand(query, con);
            pool_info = new string[8];
            SqlDataReader dr;

            dr = cmd.ExecuteReader();
            if (dr.Read())
            {

                if (check_db == "IR04R")
                {
                    pool_info[0] = dr["root"].ToString();
                    pool_info[1] = dr["name_base"].ToString();
                    pool_info[2] = dr["state"].ToString();
                    pool_info[3] = dr["city"].ToString();
                    pool_info[4] = dr["collectionName"].ToString();

                    //make string for send to client
                    result_req_client = pool_info[0] + "#" + pool_info[1] + "#" + pool_info[2] + "-" + pool_info[3]
                                        + "#" + pool_info[4];
                }
                else if (check_db == "IR04M")
                {
                    pool_info[0] = dr["root"].ToString();
                    pool_info[1] = dr["name_base"].ToString();
                    pool_info[2] = dr["name_m"].ToString();
                    pool_info[3] = dr["state"].ToString();
                    pool_info[4] = dr["city"].ToString();
                    pool_info[5] = dr["collectionName"].ToString();

                    //make string for send to client
                    result_req_client = pool_info[0] + "#" + pool_info[1] + "#" + pool_info[2] + "#" + pool_info[3]
                                        + "-" + pool_info[4] + "#" + pool_info[5];

                }
                else if (check_db == "IR04S")
                {
                    pool_info[0] = dr["root"].ToString();
                    pool_info[1] = dr["name_base"].ToString();
                    pool_info[2] = dr["name_m"].ToString();
                    pool_info[3] = dr["name_s"].ToString();
                    pool_info[4] = dr["state"].ToString();
                    pool_info[5] = dr["city"].ToString();
                    pool_info[6] = dr["collectionName"].ToString();


                    //make string for send to client
                    result_req_client = pool_info[0] + "#" + pool_info[1] + "#" + pool_info[2] + "#" + pool_info[3]
                                        + "#" + pool_info[4] + "-" + pool_info[5] + "#" + pool_info[6];

                }
                else if (check_db == "IR04C")
                {
                    pool_info[0] = dr["root"].ToString();
                    pool_info[1] = dr["name_base"].ToString();
                    pool_info[2] = dr["name_m"].ToString();
                    pool_info[3] = dr["name_s"].ToString();
                    pool_info[4] = dr["name_c"].ToString();
                    pool_info[5] = dr["state"].ToString();
                    pool_info[6] = dr["city"].ToString();
                    pool_info[7] = dr["collectionName"].ToString();

                     //make string for send to client
                    result_req_client = pool_info[0] + "#" + pool_info[1] + "#" + pool_info[2] + "#" + pool_info[3]
                                        + "#" + pool_info[4] + "#" + pool_info[5] + "-" + pool_info[6] + "#" + pool_info[7];

                }


            }

            dr.Close();
            con.Close();
            
            SqlConnection.ClearPool(con);

        }
        public void check_active_code(string query, string check_db, string _ip, string _port, string _conStr)
        { 
//check client active code
            {
                con_db();
                cmd = new SqlCommand(query, con);
                pool_info = new string[1];
                SqlDataReader dr;
                string query_fetch;
                dr = cmd.ExecuteReader();
                if (dr.Read())
                {

                    if (check_db == "IR04R")
                    {
                        
                        del_update_insert("UPDATE tbl_srv_1 SET active_flag_r = 'True' , ip_r = '"
                            + _ip + "' , port_r = '" + _port + "' , con_str_r = '" + _conStr
                            + "' WHERE active_code_r = '" + (dr["active_code_r"].ToString()) + "'");

                      //fetch of db
                        query_fetch = "SELECT root , name_base , state , city , collectionName FROM view_sub_1 WHERE  active_code_r = '" + (dr["active_code_r"].ToString()) + "'";
                        get_req(query_fetch, check_db);

                    }
                    else if (check_db == "IR04M")
                    {
                        del_update_insert("UPDATE tbl_srv_2 SET active_flag_m = 'True' , ip_m = '"
                            + _ip + "' , port_m = '" + _port + "' , con_str_m = '" + _conStr
                            + "' WHERE active_code_m = '" + (dr["active_code_m"].ToString()) + "'");

                        query_fetch = "SELECT root , name_base , name_m , state , city , collectionName FROM view_sub_master WHERE  active_code_m = '" + (dr["active_code_m"].ToString()) + "'";
                        get_req(query_fetch, check_db);

                    }
                    else if (check_db == "IR04S")
                    {
                        del_update_insert("UPDATE tbl_srv_3 SET active_flag_s = 'True' , ip_s = '"
                            + _ip + "' , port_s = '" + _port + "' , con_str_s = '" + _conStr
                            + "' WHERE active_code_s = '" + (dr["active_code_s"].ToString()) + "'");

                        query_fetch = "SELECT root , name_base , name_m , name_s , state , city , collectionName FROM view_sub_slave WHERE  active_code_s = '" + (dr["active_code_s"].ToString()) + "'";
                        get_req(query_fetch, check_db);

                    }
                    else if (check_db == "IR04C")
                    {
                        del_update_insert("UPDATE tbl_4 SET active_flag_c = 'True' , ip_c = '"
                            + _ip + "' , port_c = '" + _port + "' , con_str_c = '" + _conStr
                            + "' WHERE active_code_c = '" + (dr["active_code_c"].ToString()) + "'");

                        query_fetch = "SELECT root , name_base , name_m , name_s , name_c , state , city , collectionName FROM view_sub_client WHERE  active_code_c = '" + (dr["active_code_c"].ToString()) + "'";
                        get_req(query_fetch, check_db);
                    }


                }
                else
                {
                    result_req_client = "your requst is incorrect...";
                }

                dr.Close();

                con.Close();
                SqlConnection.ClearPool(con);
            }//end public void get_ip_port


        }
    }
//-------------------*******************-------------------
//-------------------*******************-------------------



please help me!


please help me!

推荐答案

u write the log file and then how its break process. any help how to write log file



retweet me
u write the log file and then how its break process. any help how to write log file

retweet me


这篇关于为什么不回答我的Windows服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆