UDP監聽軟件代碼

UDPSever.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Text.RegularExpressions; using System.Net; using System.Net.Sockets; using System.Threading; namespace UDPListenPorts { public partial class UDPSever : Form { /*聲明瞭一個事件MessageArrived,聲明事件以前咱們先聲明瞭一個名爲MessageHandler的委託。 * 能夠看出,與委託有明顯的區別,事件不是一個類型,而是類的一個成員,是屬於類的,和字 * 段、屬性、方法同樣,都是類的一部分。聲明MessageArrived事件須要使用關鍵字event,並 * 在前面加上委託類型的名稱,若是不加關鍵字event就和上文所述的聲明委託變量同樣了。事 * 件前面的委託類型說明,處理事件的函數必須符合委託所指定的原型形式。*/ ConnectSql connectsql = new ConnectSql(); public UdpClient ReceiveUdpClient; bool isTrue = false; Thread myThread; /// 
        /// 偵聽端口名稱 /// 
        public int PortName; /// 
        /// 本地地址 /// 
        public IPEndPoint LocalIPEndPoint; /// 
        /// 本地IP地址 /// 
        public IPAddress MyIPAddress; public UDPSever() { InitializeComponent(); //connectsql.Insert("","127.0.0.1","00");
 connectsql.Delete(); //connectsql.Create(); //獲取本機可用IP地址
            IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName()); foreach (IPAddress ipa in ips) { if (ipa.AddressFamily == AddressFamily.InterNetwork) { MyIPAddress = ipa;//獲取本地IP地址
                    break; } } } /// 
        /// 接收數據 /// 
        private void ReceiveData(object obj) { IPEndPoint remote = new IPEndPoint(IPAddress.Any,PortName); while (true) { try { //關閉udpClient 時此句會產生異常
                    byte[] receiveBytes = ReceiveUdpClient.Receive(ref remote); string receiveMessage = Encoding.Default.GetString(receiveBytes, 0, receiveBytes.Length); string datetime = DateTime.Now.ToString(); Messages(tbx_Show, string.Format("{0} 來自 {1} : {2} ", datetime, remote, receiveMessage)); ChangeDataGridView(dgv_Content, datetime, remote.ToString(), receiveMessage); } catch (Exception ex) { Messages(tbx_Show, ex.Message); Messages(tbx_Show, "UDP監聽已經成功關閉"); break; } } } public void Thread_Listen() { //建立一個線程接收遠程主機發來的信息
            myThread = new Thread(ReceiveData); //myThread.IsBackground = true;
 myThread.Start(); isTrue = true; Messages(tbx_Show,"UDP監聽已經成功啓動"); } //監聽
        private void btn_Listen_Click(object sender, EventArgs e) { if (!isTrue) { PortName = Convert.ToInt32(cbx_Port.Text.ToString(), 10); IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName()); foreach (IPAddress ipa in ips) { if (ipa.AddressFamily == AddressFamily.InterNetwork) { MyIPAddress = ipa;//獲取本地IP地址
                        break; } } IPEndPoint remote = new IPEndPoint(MyIPAddress, PortName); ReceiveUdpClient = new UdpClient(remote); Reset_DataGridView(); //建立一個線程接收遠程主機發來的信息
 Thread_Listen(); btn_Listen.Text = "中止"; } else { if (myThread != null) { myThread.Abort(); } //myThread.Join();
                if (ReceiveUdpClient != null) { ReceiveUdpClient.Close(); isTrue = false; btn_Listen.Text = "開始監聽"; } } } //從新刷新DataGridView
        private void Reset_DataGridView() { dgv_Content.DataSource = null; dgv_Content.Columns.Clear(); DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn(); //設置column屬性如: column.HeaderText = "列名";
            column.HeaderText = "Time"; dgv_Content.Columns.Add(column); DataGridViewTextBoxColumn column1 = new DataGridViewTextBoxColumn(); //設置column屬性如: column.HeaderText = "列名";
            column1.HeaderText = "IP"; dgv_Content.Columns.Add(column1); DataGridViewTextBoxColumn column2 = new DataGridViewTextBoxColumn(); //設置column屬性如: column.HeaderText = "列名";
            column2.HeaderText = "Content"; dgv_Content.Columns.Add(column2); dgv_Content.Columns[0].Width = 150; dgv_Content.Columns[1].Width = 145; dgv_Content.Columns[2].Width = dgv_Content.Width - dgv_Content.Columns[0].Width - dgv_Content.Columns[1].Width; } public delegate void MessageDelegate(TextBox txtbox, string Messages);//委託文本框 //文本框Invoke方法須要建立一個委託。你能夠事先寫好函數和與之對應的委託
        private void Messages(TextBox txtbox,string message) { if (txtbox.InvokeRequired) { MessageDelegate showMessageDelegate = Messages; txtbox.Invoke(showMessageDelegate, new object[] { txtbox, message }); } else { tbx_Show.Text += message + "\r\n"; } } public delegate void DelegateChangeDataGridView(DataGridView dgv_data, string time, string ip, string data);//委託DataGridView //委託DataGridView控件顯示列的文本
        void ChangeDataGridView(DataGridView dgv_data,string time, string ip, string data) { if (dgv_data.InvokeRequired) { DelegateChangeDataGridView showMessageDelegate = ChangeDataGridView; dgv_data.Invoke(new DelegateChangeDataGridView(showMessageDelegate), new object[] { dgv_data, time, ip, data }); } else { int index = dgv_Content.Rows.Add(); dgv_data.Rows[index].Cells[0].Value = time; dgv_data.Rows[index].Cells[1].Value = ip; dgv_data.Rows[index].Cells[2].Value = data; Match ipRegex = Regex.Match(ip, @"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}"); if (ipRegex.Success) { if (!this.IPList.Items.Contains(ipRegex.Value)) { // 向listBox中插入數據
                        this.IPList.Items.Add(ipRegex.Value); } connectsql.Insert(time, ipRegex.Value, data);//將數據存到數據庫
 } } } /// <summary>
        /// 大小更改時,DataGridView列表的寬度改變 /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UDPSever_SizeChanged(object sender, EventArgs e) { dgv_Content.Columns[2].Width = dgv_Content.Width - dgv_Content.Columns[0].Width - dgv_Content.Columns[1].Width; } //篩選IP
        private void IPList_SelectedIndexChanged(object sender, EventArgs e) { if (myThread != null) { myThread.Abort(); } if (ReceiveUdpClient != null) { ReceiveUdpClient.Close(); isTrue = false; btn_Listen.Text = "開始監聽"; } try { dgv_Content.Columns.Clear(); DataTable dt = connectsql.Select(IPList.SelectedItem.ToString(), dgv_Content); dgv_Content.DataSource = dt; dgv_Content.Columns[0].Width = 150; dgv_Content.Columns[1].Width = 145; dgv_Content.Columns[2].Width = dgv_Content.Width - dgv_Content.Columns[0].Width - dgv_Content.Columns[1].Width; } catch (Exception ex) { MessageBox.Show(ex.Message); } } //清空全部數據
        private void btn_Clear_Click(object sender, EventArgs e) { dgv_Content.DataSource = null; IPList.Items.Clear(); tbx_Show.Text = ""; IPList.Items.Add("IP列表"); } //public delegate void DelegateSql();//委託DataGridView

        private void UDPSever_FormClosed(object sender, FormClosedEventArgs e) { if (ReceiveUdpClient != null) { ReceiveUdpClient.Close(); } if (myThread != null) { myThread.Abort(); } this.Dispose(); System.Environment.Exit(0); } } } ConnectSql.cs using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Windows.Forms; using System.Data.SqlServerCe; namespace UDPListenPorts { class ConnectSql { SqlCeConnection conn; //聲明
        public SqlCeConnection Connect() { //string connectionStr = @"Data Source=GFOC4K9TL9GN0Z9;Initial Catalog=UDPListen;User ID=sa;Password=***********;Integrated Security=True;Connect Timeout=30";//             string connectionStr = @"Data Source=" + Application.StartupPath + @"\UDPListen.sdf";//Integrated Security=True;Connect Timeout=30
            conn = new SqlCeConnection(connectionStr); return conn; } /// <summary>
        /// 向表中插入所接收的數據 /// </summary>
        /// <param name="time">時間</param>
        /// <param name="ip">ip</param>
        /// <param name="data">data</param>
        public void Insert(string time, string ip, string data) { conn = Connect(); string Insert_Str = "INSERT INTO [UDPlisten](Time,IP,Content) VALUES('" + time + "','" + ip + "','" + data + "')"; SqlCeCommand cmd = new SqlCeCommand(Insert_Str, conn);//建立命令
 conn.Open(); cmd.ExecuteNonQuery();//執行命令
 conn.Close(); } /// <summary>
        /// 從表中查詢所需的數據 /// </summary>
        /// <param name="ip">傳入選中的IP</param>
        /// <param name="dgv">傳入要綁定的DataGridView控件名</param>
        /// <returns></returns>
        public DataTable Select(string ip, DataGridView dgv) { conn = Connect(); conn.Open(); DataRow row; DataTable _table = CreateDataTable(); try { if (ip == "IP列表") { string Select_Str = @"SELECT Time,IP, Content FROM UDPlisten"; SqlCeDataAdapter sda = new SqlCeDataAdapter();//用於填充 DataSet 和更新 SQL Server 數據庫的一組數據命令和一個數據庫鏈接
                    SqlCeCommand sqlComm = new SqlCeCommand(Select_Str, conn); //sqlComm.ExecuteNonQuery();
                    SqlCeDataReader sdrr = sqlComm.ExecuteReader(); while (sdrr.Read()) { //int count = sdrr.FieldCount;
                        row = _table.NewRow(); row["Time"] = sdrr[0]; row["IP"] = sdrr[1]; row["Content"] = sdrr[2]; _table.Rows.Add(row); } int i = _table.Rows.Count; } else { string Select_Str = @"SELECT Time,IP, Content FROM UDPlisten WHERE IP=" + "'" + ip.ToString() + "'"; SqlCeDataAdapter sda = new SqlCeDataAdapter();//用於填充 DataSet 和更新 SQL Server 數據庫的一組數據命令和一個數據庫鏈接
                    SqlCeCommand sqlComm = new SqlCeCommand(Select_Str, conn); //sqlComm.ExecuteNonQuery();
                    SqlCeDataReader sdrr = sqlComm.ExecuteReader(); while (sdrr.Read()) { //int count = sdrr.FieldCount;
                        row = _table.NewRow(); row["Time"] = sdrr[0]; row["IP"] = sdrr[1]; row["Content"] = sdrr[2]; _table.Rows.Add(row); } int i = _table.Rows.Count; } //dgv.DataSource = _table;
 } catch (Exception ex) { MessageBox.Show(ex.Message); } return _table; } //Create DataTable Rows and Column
        private static DataTable CreateDataTable() { //Create new DataTable
            DataTable _table = new DataTable(); //Declare DataColumn and DataRow variables;
 DataColumn column; column = new DataColumn(); column.DataType = System.Type.GetType("System.String"); column.ColumnName = "Time"; _table.Columns.Add(column); column = new DataColumn(); column.DataType = System.Type.GetType("System.String"); column.ColumnName = "IP"; _table.Columns.Add(column); column = new DataColumn(); column.DataType = System.Type.GetType("System.String"); column.ColumnName = "Content"; _table.Columns.Add(column); return _table; } public void Delete() { conn = Connect(); conn.Open(); //DelegateSql delegat = Delete;
            string Select_Str = @"Delete FROM UDPlisten"; SqlCeCommand sqlComm = new SqlCeCommand(Select_Str, conn); sqlComm.ExecuteNonQuery(); //SqlCeDataReader sdrr = sqlComm.ExecuteReader();
 conn.Close(); } //public void Create() //{ //    //SqlCeEngine engine = new SqlCeEngine(@"Data Source=" + Application.StartupPath + @"\UDPListen.sdf"); //    //engine.CreateDatabase(); //    //SqlCeConnection ssceconn = new SqlCeConnection(@"Data Source=" + Application.StartupPath + @"\UDPListen.sdf"); //   // ssceconn.Open(); //    //SqlCeCommand sqlCreateTable = ssceconn.CreateCommand(); //   // sqlCreateTable.CommandText = "CREATE TABLE UDPlisten(ID int IDENTITY(0,1) PRIMARY KEY,Time nvarchar(100), IP nvarchar(100),Content nvarchar(10))"; //   // sqlCreateTable.ExecuteNonQuery(); //   // ssceconn.Close(); //}
 } } 
View Code
相關文章
相關標籤/搜索