111,094
社区成员




private void Btn_Start_Click(object sender, EventArgs e)
{
if (Btn_Start.Text == "发送")
{
Btn_Start.Text = "停止";
SendStatusLabel.Text = ("发送成功!");
Config_groupBox.Enabled = false;
File_groupBox.Enabled = false;
//Statistics_groupBox.Enabled = false;
try
{
UdpDataSend = new Thread(new ThreadStart(DataSend));
UdpDataSend.Priority = ThreadPriority.Normal;
UdpDataSend.IsBackground = true;
UdpDataSend.Start(); ////////////////////////这里起一个线程用来发包
timer = new System.Timers.Timer(TimeBlank);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();///////////////////////////////这个timer是用来统计流量的
}
catch (Exception ex) { throw ex; }
}
else if (Btn_Start.Text == "停止")
{
Btn_Start.Text = "发送";
SendStatusLabel.Text = ("发送已停止!");
Config_groupBox.Enabled = true;
File_groupBox.Enabled = true;
//Statistics_groupBox.Enabled = true;
UdpDataSend.Abort();
}
}
int LoopCount = 0;
byte[] Msg_DataPackage = null;
Socket udpclient_Socket;
UdpClient udpclient;
IPEndPoint ipEndPoint;
///////////////////////////////////////发包的函数,从我的表格里读取参数,表格一行代表一个包的参数,所以每次循///////////////////////////////////////环表有多少行就发多少个包
private void DataSend2()
{
lock (this)
{
while (Thread.CurrentThread.ThreadState.Equals(ThreadState.Background))
{
LoopCount++;
for (int i = 0; i < UDP_Table.RowCount; i++)
{
if (udpclient != null)
{
udpclient.Release();
}
BitJudge(tableModel.Rows[i].Cells[3].Text, out BitArray);
if (BitArray[5] == true)
{
/////////////第一种udpclient的方式,直接用send同步发送或者用BeginSend异步发送
//ipEndPoint = new IPEndPoint(IPAddress.Parse(tableModel.Rows[i].Cells[7].Text), Convert.ToInt32(tableModel.Rows[i].Cells[8].Text));
//udpclient = new UdpClient(LocalPort);
/////////////第二种socket的方式SocketType可用Dgram或者Ram
udpclient_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Udp);
IPAddress remoteIp = IPAddress.Parse(tableModel.Rows[i].Cells[7].Text);
////////////组包函数
Msg_SourceData(tableModel.Rows[i].Cells[1].Text,
Convert.ToInt32(tableModel.Rows[i].Cells[2].Text),
tableModel.Rows[i].Cells[3].Text,
tableModel.Rows[i].Cells[4].Text,
LoopCount,
tableModel.Rows[i].Cells[5].Text,
tableModel.Rows[i].Cells[6].Text,
tableModel.Rows[i].Cells[9].Text,
out Msg_DataPackage);
//////////////发送部分
//udpclient.Send(Msg_DataPackage, Msg_DataPackage.Length, ipEndPoint);
//udpclient.BeginSend(Msg_DataPackage, Msg_DataPackage.Length, ipEndPoint, new AsyncCallback(SendCallback), udpclient);
//udpclient.Close();
udpclient_Socket.SendTo(Msg_DataPackage, new IPEndPoint(remoteIp, LocalPort));
udpclient_Socket.Close();
AllPackageCount++;
AllSizeCount += Convert.ToUInt64(tableModel.Rows[i].Cells[2].Text) + 28;
}
}
}
}
}
/////////////////////updclient异步发送时的回调函数
public void SendCallback(IAsyncResult ar)
{
if (udp != null)
{
udp.Close();
}
}