开源一个监听指定IP,端口,并捕获通过此端口消息的类

using System;

using System.Text;
using System.Net.Sockets;
using System.Net;

namespace myClass
{
    class clsListenPort
    {
        #region 使用说明
        /*
            用途:监听某IP,指定端口,捕获通过此端口的消息。
            举例:
            private delegate void ListenPostModel(string strData);//监听端口
                
            myClass.clsListenPort myListenPort = new myClass.clsListenPort("LocalHost",8008);
            myListenPort.GetMessage += new myClass.clsListenPort.GetMessageEventHandler(m_GetMessage);
            myListenPort.GetMessageError += new myClass.clsListenPort.GetMessageErrorEventHandler(m_GetMessageError);
            myListenPort.m_StartDoListen();//开始监听

            //捕获到消息事件
            private void m_GetMessage(myClass.clsListenPort sender, string data)
            {
                ListenPostModel dh = new ListenPostModel(m_ProcessMsg); //invokes为方法名
                this.Invoke(dh, new object[] { data });// step3 调用invoke
            }

            private void m_ProcessMsg(string strMessage)
            {
                lst网络通信.Items.Add(strMessage);//显示通信消息
            }

            //Error消息事件
            private void m_GetMessageError(myClass.clsListenPort sender, string data)
            {
                ListenPostModel dh = new ListenPostModel(m_ProcessMsgError); //invokes为方法名
                this.Invoke(dh, new object[] { data });// step3 调用invoke
            }

            private void m_ProcessMsgError(string strMessage)
            {
                lst网络通信1.Items.Add(strMessage);//显示通信消息
            }
           
            //关闭监听,停止线程
            if (myListenPort != null)
            {
                myListenPort.m_Close();
            }
         */
        #endregion

        #region 私有变量
        private bool bolIsListen = true;
        private string strIPAddress;//IP地址
        private int intPost;//端口
        #endregion

        #region 委托,事件
        //捕获到消息
        public delegate void GetMessageEventHandler(clsListenPort sender, string Data);
        private GetMessageEventHandler GetMessageEvent;

        public event GetMessageEventHandler GetMessage
        {
            add
            {
                GetMessageEvent = (GetMessageEventHandler)System.Delegate.Combine(GetMessageEvent, value);
            }
            remove
            {
                GetMessageEvent = (GetMessageEventHandler)System.Delegate.Remove(GetMessageEvent, value);
            }
        }
        //异常
        public delegate void GetMessageErrorEventHandler(clsListenPort sender, string Data);
        private GetMessageErrorEventHandler GetMessageErrorEvent;

        public event GetMessageErrorEventHandler GetMessageError
        {
            add
            {
                GetMessageErrorEvent = (GetMessageErrorEventHandler)System.Delegate.Combine(GetMessageErrorEvent, value);
            }
            remove
            {
                GetMessageErrorEvent = (GetMessageErrorEventHandler)System.Delegate.Remove(GetMessageErrorEvent, value);
            }
        }
        #endregion

        public clsListenPort(string IPAddress, int Post)
        {
            strIPAddress = IPAddress;
            intPost = Post;
        }

        /// <summary>
        /// 开始后台线程,开始侦听网络/端口
        /// </summary>
        public void m_StartDoListen()
        {
            System.Threading.Thread listenerThread = new System.Threading.Thread(new System.Threading.ThreadStart(m_DoListen));
            listenerThread.Start();
        }

        /// <summary>
        /// 开始监听
        /// </summary>
        public void m_DoListen()
        {
            try
            {
                Socket ssock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress hostIp = Dns.GetHostEntry(strIPAddress).AddressList[0];
                IPEndPoint ep = new IPEndPoint(hostIp, intPost);
                ssock.Bind(ep); //绑定

                ssock.Listen(32); //开始侦听

                while (bolIsListen)
                {
                    Socket sock = ssock.Accept(); //等待客户端请求
                    string file="";
                    try
                    {
                        file = getRequest(sock);

                        if (file == "ShutdownListener")//停止侦听,释放端口
                        {
                            bolIsListen = false;
                            ssock.Close();//关闭连接
                            break;//退出 循环
                        }

                        if (GetMessageEvent != null)//执行事件
                            GetMessageEvent(this, file);         
                    }
                    catch (Exception ex)
                    {
                        if (GetMessageErrorEvent != null)//执行事件
                            GetMessageErrorEvent(this, ex.Message);
                    }
                    finally
                    {
                        sock.Shutdown(SocketShutdown.Both);//关闭连接
                        sock.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                if (GetMessageErrorEvent != null)//执行事件
                    GetMessageErrorEvent(this, ex.Message);
            }
        }

        /// <summary>
        /// //停止侦听,释放端口,释放资源
        /// </summary>
        public void m_Close()
        {
            try
            {
                System.Windows.Forms.WebBrowser myWeb = new System.Windows.Forms.WebBrowser();
                string strPath = "http://" + strIPAddress + ":" + intPost.ToString() + "/ShutdownListener";
                myWeb.Navigate(strPath);//http://localhost:8008/ShutdownListener");
            }
            catch (Exception ex)
            {
                 if (GetMessageErrorEvent != null)//执行事件
                    GetMessageErrorEvent(this, ex.Message);
            }
        }

        /// <summary>
        /// 读取请求信息,返回客户端请求的文件名
        /// </summary>
        /// <returns></returns>
        private string getRequest(Socket sock)
        {
            string s = null;
            byte[] buff = new byte[1024];
            int recCount = 0;
            try
            {
                //从socket读取请求信息
                recCount = sock.Receive(buff, buff.Length, SocketFlags.None);
                s = ASCIIEncoding.ASCII.GetString(buff, 0, recCount);

                if (s.IndexOf("GET") > -1)
                {
                    s = s.Substring(5);
                    int fend = s.IndexOf(" ");
                    s = s.Substring(0, fend); //取得请求文件的路径及文件名
                }
                return ProcessString(s);
            }
            catch (Exception ex)
            {
                if (GetMessageErrorEvent != null)//执行事件
                    GetMessageErrorEvent(this, ex.Message);
            }
            return "";
        }

        /// <summary>
        /// 把客户端请求文件中的字符替换掉
        /// </summary>
        /// <param name="input">要处理的字符串</param>
        /// <returns></returns>
        private string ProcessString(string input)
        {
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < input.Length; i++)
            {
                if (input[i] == '/')
                {
                    result.Append('\\');
                }
                else
                {
                    result.Append(input[i]);
                }
            }
            return result.ToString();
        }
    }
}

posted @ 2010-07-18 16:11  海乐学习  阅读(3464)  评论(0编辑  收藏  举报