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();
//}
}
}