-
Notifications
You must be signed in to change notification settings - Fork 110
/
mainwindow.cpp
834 lines (761 loc) · 29.5 KB
/
mainwindow.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTranslator>
#include "define.h"
#include <QMessageBox>
#include <stdlib.h>
#include <QFileDialog>
#include <QFile>
#include <QString>
#include <QTimer>
#include <QInputDialog>
#include <QDateTime>
const char toHex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//设置程序的开启默认画面
setUdpGuiExt();
//获取本机的IP地址,并初始化相应的控件属性和变量
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
// use the first non-localhost IPv4 address
for(int i = 0; i < ipAddressesList.size(); ++i) {
if(ipAddressesList.at(i) != QHostAddress::LocalHost && ipAddressesList.at(i).toIPv4Address()) {
m_ip = ipAddressesList.at(i).toString();
break;
}
}
// 设置获取的IP到相应文本框
ui->lEditIpAddr->setText(m_ip);
ui->lEditUdpIP->setText(m_ip);
ui->SndProgressBar->setVisible(false);
//初始化全局变量
rmtServerIP = new QHostAddress();
rcvDataCnt = 0;
sndDataCnt = 0;
TcpClientLinkCnt = 0;
//NetState = false;
loopSending = false;
CurIPPort = "";
CurPath = "";
curFile = 0;
}
MainWindow::~MainWindow()
{
delete ui;
}
/**********************************************************/
//Function for connection button
void MainWindow::on_pBtnNetCnnt_clicked(bool checked)
{
if(checked) { //切换到链接状态
if(ui->cBoxNetType->currentIndex() == UDP_MODE) {
//建立UDP链接
udpSocket = new QUdpSocket(this);
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(udpDataReceived()));
lhAddr.setAddress(ui->lEditIpAddr->text());
lhPort = ui->lEditIpPort->text().toInt();
rmtAddr.setAddress(ui->lEditUdpIP->text());
rmtPort = ui->lEditUdpPort->text().toInt();
bool result = udpSocket->bind(lhPort);
if(!result)
{
ui->pBtnNetCnnt->setChecked(0);
QMessageBox::information(this, tr("错误"), tr("UDP绑定端口失败!"));
return;
}
ui->CurState->setText(tr("建立UDP连接成功"));
} else if(ui->cBoxNetType->currentIndex() == TCP_SERVER_MODE) {
//建立TCP服务器链接
lhAddr.setAddress(ui->lEditIpAddr->text());
lhPort = ui->lEditIpPort->text().toInt();
if(! slotTryCreateTcpServer())
{
ui->pBtnNetCnnt->setChecked(0);
QMessageBox::information(this, tr("错误"), tr("尝试建立服务器失败! 请确认网络状态和端口。"));
return;
}
ui->CurState->setText(tr("建立TCP服务器成功"));
} else if(ui->cBoxNetType->currentIndex() == TCP_CLIENT_MODE) {
//建立TCP客户端
QString ip = ui->lEditIpAddr->text();
if(!rmtServerIP->setAddress(ip))
{
QMessageBox::information(this, tr("错误"), tr("TCP服务器IP设置失败!"));
return;
}
tcpClientSocket = new QTcpSocket(this);
connect(tcpClientSocket, SIGNAL(readyRead()), this, SLOT(tcpClientDataReceived()));
tcpClientSocket->connectToHost(*rmtServerIP, ui->lEditIpPort->text().toInt());
if(!tcpClientSocket->waitForConnected(2000)) {
ui->lEditUdpPort->setText(QString::number(0, 10));
ui->pBtnNetCnnt->setChecked(0);
QMessageBox::information(this, tr("错误"), tr("尝试连接服务器失败! 请确认服务器状态。"));
return;
}
ui->lEditUdpPort->setText(QString::number(tcpClientSocket->localPort(), 10));
ui->CurState->setText(tr("连接TCP服务器成功"));
}
ui->pBtnNetCnnt->setText(tr("断开网络"));
ui->pBtnSendData->setEnabled(true);
//NetState = true;
} else { //切换到断开状态
if(ui->cBoxNetType->currentIndex() == UDP_MODE) {
//断开UDP链接
udpSocket->close();
delete udpSocket;
} else if(ui->cBoxNetType->currentIndex() == TCP_SERVER_MODE) {
//断开TCP服务器链接
slotDeleteTcpServer();
} else if(ui->cBoxNetType->currentIndex() == TCP_CLIENT_MODE) {
//断开TCP客户端链接
tcpClientSocket->disconnectFromHost();
}
ui->pBtnNetCnnt->setText(tr("连接网络"));
ui->pBtnSendData->setEnabled(false);
ui->CurState->setText(tr(""));
// NetState = false;
}
}
/**********************************************************/
//funcions switch
void MainWindow::on_cBoxNetType_currentIndexChanged(int index)
{
if(index == UDP_MODE) {
setUdpGuiExt();
ui->label_Port->setText(tr("本地端口"));
ui->label_IP->setText(tr("本地IP地址"));
ui->labelUdp->setText(tr("目标IP地址"));
ui->labelUdp1->setText(tr("目标端口"));
ui->lEditIpAddr->setText(m_ip);
} else if(index == TCP_SERVER_MODE) {
setTcpSvrGuiExt();
// setTcpClientGuiExt();
ui->label_Port->setText(tr("本地端口"));
ui->label_IP->setText(tr("本地IP地址"));
ui->lEditIpAddr->setText(m_ip);
} else if(index == TCP_CLIENT_MODE) {
setTcpClientGuiExt();
ui->label_Port->setText(tr("服务器端口"));
ui->label_IP->setText(tr("服务器IP地址"));
ui->labelUdp->setText(tr("本地IP地址"));
ui->labelUdp1->setText(tr("本地端口"));
ui->lEditIpAddr->setText(tr("220.165.9.87"));
}
}
/**********************************************************/
//set UDP mode
void MainWindow::setUdpGuiExt()
{
ui->labelSpaceUdp->setVisible(true);
ui->lEditUdpIP->setVisible(true);
ui->labelUdp->setVisible(true);
ui->labelUdp1->setVisible(true);
ui->lEditUdpPort->setVisible(true);
ui->labelClients->setVisible(false);
ui->cBoxClients->setVisible(false);
ui->labelSpaceClients->setVisible(false);
ui->cBox_chatMode->setVisible(false);
ui->cBox_echoMode->setVisible(false);
}
/**********************************************************/
//set TCP server
void MainWindow::setTcpSvrGuiExt()
{
ui->labelSpaceUdp->setVisible(false);
ui->lEditUdpIP->setVisible(false);
ui->labelUdp->setVisible(false);
ui->labelUdp1->setVisible(false);
ui->lEditUdpPort->setVisible(false);
ui->labelClients->setVisible(true);
ui->cBoxClients->setVisible(true);
ui->labelSpaceClients->setVisible(true);
ui->cBox_chatMode->setVisible(true);
ui->cBox_echoMode->setVisible(true);
}
/**********************************************************/
void MainWindow::setTcpClientGuiExt()
{
ui->labelSpaceUdp->setVisible(true);
ui->lEditUdpIP->setVisible(true);
ui->labelUdp->setVisible(true);
ui->labelUdp1->setVisible(true);
ui->lEditUdpPort->setVisible(true);
ui->labelClients->setVisible(false);
ui->cBoxClients->setVisible(false);
ui->labelSpaceClients->setVisible(false);
ui->cBox_chatMode->setVisible(false);
ui->cBox_echoMode->setVisible(false);
}
/**********************************************************/
//send data
void MainWindow::on_pBtnSendData_clicked()
{
if(ui->cBoxStartSndFile->checkState()) {
on_pBtnResetCnt_clicked();
ui->pBtnSendData->setText(tr("正在发送"));
ui->pBtnSendData->setEnabled(false);
insertDateTimeInRcvDisp();
ui->ReceiveTextEdit->appendPlainText(tr("开始发送..."));
toSendFile();
insertDateTimeInRcvDisp();
ui->ReceiveTextEdit->appendPlainText(tr("发送完成!"));
float hasSnd = sndDataCnt;
hasSnd = hasSnd / 1024 / 1024;
QString hasSndSz = QString("%1").arg(hasSnd);
ui->ReceiveTextEdit->appendPlainText(tr("共发送数据:") + hasSndSz + "MB");
ui->pBtnSendData->setText(tr("发送"));
ui->pBtnSendData->setEnabled(true);
return;
}
if(ui->tEditSendText->toPlainText().size() == 0) {
QMessageBox::information(this, tr("提示"), tr("发送区为空,请输入内容。"));
return; //如果发送区为空则直接跳出
}
if(ui->cBoxLoopSnd->checkState())
{
if(!loopSending) {
ui->pBtnSendData->setText(tr("停止发送"));
timer->start();
loopSending = true;
} else {
timer->stop();
ui->pBtnSendData->setText(tr("发送"));
loopSending = false;
}
} else {
toSendData();
if(ui->cBox_AntoClearSnd->checkState()) {
ui->tEditSendText->clear();
}
}
}
/**********************************************************/
//send data
void MainWindow::toSendData()
{
QByteArray datagram;
if(ui->cBox_SndHexDisp->checkState()) {
QStringList hexStr = ui->tEditSendText->toPlainText().split(" ", QString::SkipEmptyParts);
int hexSize = hexStr.size();
for(int i = 0; i < hexSize; i++) {
QString hexSubStr = hexStr.at(i);
datagram.append(ConvertHexStr(hexSubStr));
}
datagram.resize(hexSize);
} else {
datagram = ui->tEditSendText->toPlainText().toLocal8Bit();
}
if(datagram.size() == 0)
return;
if(ui->cBoxNetType->currentIndex() == UDP_MODE) {
udpSocket->writeDatagram(datagram.data(), datagram.size(), rmtAddr, rmtPort);
} else if(ui->cBoxNetType->currentIndex() == TCP_SERVER_MODE) {
int idx = ui->cBoxClients->currentIndex() ;
if(idx == 0) {
emit sendDataToClient((char *)datagram.data(), datagram.size(), 0, 0);
} else {
emit sendDataToClient((char *)datagram.data(), datagram.size(), tcpClientSocketDescriptorList.at(idx), 0);
}
} else if(ui->cBoxNetType->currentIndex() == TCP_CLIENT_MODE) {
tcpClientSocket->write(datagram.data(), datagram.size());
}
sndDataCnt += datagram.size();
ui->lEdit_SndCnt->setText(QString::number(sndDataCnt, 10));
}
/**********************************************************/
void MainWindow::toSendFile()
{
if(curFile == 0)
return;
char buf[1024];
int rdLen = 0;
ui->SndProgressBar->setMaximum(curFile->bytesAvailable());
ui->SndProgressBar->setVisible(true);
ui->SndProgressBar->setValue(0);
if(ui->cBoxNetType->currentIndex() == UDP_MODE) { //UDP 模式
while(!curFile->atEnd())
{
rdLen = curFile->read(buf, 1024);
udpSocket->writeDatagram(buf, rdLen, rmtAddr, rmtPort);
sndDataCnt += rdLen;
ui->lEdit_SndCnt->setText(QString::number(sndDataCnt, 10));
ui->SndProgressBar->setValue(ui->SndProgressBar->value() + rdLen);
msDelay(1);
}
} else if(ui->cBoxNetType->currentIndex() == TCP_SERVER_MODE) { //TCP服务器模式
int idx = ui->cBoxClients->currentIndex() ;
if(idx == 0) {
while(!curFile->atEnd())
{
//msDelay(2);
rdLen = curFile->read(buf, 1024);
emit sendDataToClient(buf, rdLen, 0, 0);
sndDataCnt += rdLen;
ui->lEdit_SndCnt->setText(QString::number(sndDataCnt, 10));
ui->SndProgressBar->setValue(ui->SndProgressBar->value() + rdLen);
QCoreApplication::processEvents(QEventLoop::AllEvents, 1);
}
} else {
while(!curFile->atEnd())
{
// msDelay(2);
rdLen = curFile->read(buf, 1024);
emit sendDataToClient(buf, rdLen, tcpClientSocketDescriptorList.at(idx), 0);
sndDataCnt += rdLen;
ui->lEdit_SndCnt->setText(QString::number(sndDataCnt, 10));
ui->SndProgressBar->setValue(ui->SndProgressBar->value() + rdLen);
QCoreApplication::processEvents(QEventLoop::AllEvents, 1);
}
}
} else if(ui->cBoxNetType->currentIndex() == TCP_CLIENT_MODE) {
while(!curFile->atEnd())
{
rdLen = curFile->read(buf, 1024);
tcpClientSocket->write(buf, rdLen);
//更新发送数据计数器
sndDataCnt += rdLen;
ui->lEdit_SndCnt->setText(QString::number(sndDataCnt, 10));
ui->SndProgressBar->setValue(ui->SndProgressBar->value() + rdLen);
QCoreApplication::processEvents(QEventLoop::AllEvents, 1);
}
}
ui->SndProgressBar->setVisible(false);
}
/**********************************************************/
//udp data received
void MainWindow::udpDataReceived()
{
QHostAddress address;
quint16 port;
QString tmpIPPort = "";
while(udpSocket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
udpSocket->readDatagram(datagram.data(), datagram.size(), &address, &port);
if(ui->StartRcvFile->checkState()) {
char *buf;
buf = datagram.data();
if(curFile != 0) {
curFile->write(buf, datagram.size());
}
} else {
if(!ui->cBox_PauseShowRcv->checkState()) {
tmpIPPort = address.toString() + ":" + QString::number(port, 10);
QString rcvMsg = QString::fromUtf8(datagram, datagram.size());
if(CurIPPort != tmpIPPort) {
CurIPPort = tmpIPPort;
if(ui->ReceiveTextEdit->toPlainText().size() != 0) {
ui->ReceiveTextEdit->insertPlainText("\n");
}
ui->ReceiveTextEdit->insertPlainText(tr("【数据来自") + CurIPPort + tr("】\n"));
}
//显示数据接收时间
if(ui->cBox_ShowRcvTime->checkState()) insertDateTimeInRcvDisp();
//输出数据到接收显示区
if(!ui->cBox_RcvHexDisp->checkState()) { //显示字符串
ui->ReceiveTextEdit->insertPlainText(rcvMsg);
} else { //显示十六进制字符串
for(int i = 0; i < datagram.size(); i++) {
char ch = datagram.at(i);
QString tmpStr = "";
tmpStr.append(toHex[(ch & 0xf0) / 16]);
tmpStr.append(toHex[ch & 0x0f]);
tmpStr.append(" ");
ui->ReceiveTextEdit->insertPlainText(tmpStr);
}
}
}
}
rcvDataCnt += datagram.size();
ui->lEdit_RcvCnt->setText(QString::number(rcvDataCnt, 10));
}
}
/**********************************************************/
//clear the receive editor
void MainWindow::on_pBtnClearRcvDisp_clicked()
{
ui->ReceiveTextEdit->clear();
}
/**********************************************************/
//reset the conters
void MainWindow::on_pBtnResetCnt_clicked()
{
sndDataCnt = 0;
rcvDataCnt = 0;
ui->lEdit_RcvCnt->setText(QString::number(0, 10));
ui->lEdit_SndCnt->setText(QString::number(0, 10));
}
/**********************************************************/
//UDP port changed PRC
void MainWindow::on_lEditUdpPort_textChanged(QString text)
{
rmtPort = text.toInt();
}
/**********************************************************/
//UDP IP Adderess changed PRC
void MainWindow::on_lEditUdpIP_textChanged(QString text)
{
rmtAddr.setAddress(text);
}
/**********************************************************/
// TCP Client data received
void MainWindow::tcpClientDataReceived()
{
while(tcpClientSocket->bytesAvailable() > 0)
{
QByteArray datagram;
datagram.resize(tcpClientSocket->bytesAvailable());
tcpClientSocket->read(datagram.data(), datagram.size());
if(ui->StartRcvFile->checkState()) {
char *buf;
buf = datagram.data();
if(curFile != 0) {
curFile->write(buf, datagram.size());
}
} else {
if(!ui->cBox_PauseShowRcv->checkState()) {
QString rcvMsg = QString::fromUtf8(datagram, datagram.size());
QString tmpIPPort = ui->lEditIpAddr->text() + ":" + ui->lEditIpPort->text();
if(CurIPPort != tmpIPPort) {
CurIPPort = tmpIPPort;
if(ui->ReceiveTextEdit->toPlainText().size() != 0) {
ui->ReceiveTextEdit->insertPlainText("\n");
}
ui->ReceiveTextEdit->insertPlainText(tr("【数据来自") + CurIPPort + tr("】\n"));
}
//显示数据接收时间
if(ui->cBox_ShowRcvTime->checkState()) insertDateTimeInRcvDisp();
//输出数据到接收显示区
if(!ui->cBox_RcvHexDisp->checkState()) { //显示字符串
ui->ReceiveTextEdit->insertPlainText(rcvMsg);
} else { //显示十六进制字符串
for(int i = 0; i < datagram.size(); i++) {
char ch = datagram.at(i);
QString tmpStr = "";
tmpStr.append(toHex[(ch & 0xf0) / 16]);
tmpStr.append(toHex[ch & 0x0f]);
tmpStr.append(" ");
ui->ReceiveTextEdit->insertPlainText(tmpStr);
}
}
}
}
rcvDataCnt += datagram.size();
ui->lEdit_RcvCnt->setText(QString::number(rcvDataCnt, 10));
}
}
void MainWindow::insertDateTimeInRcvDisp()
{
int year, month, day;
QDateTime::currentDateTime().date().getDate(&year, &month, &day);
QString date = QString::number(year, 10) + "-" + QString::number(month, 10) + "-" + QString::number(day, 10);
ui->ReceiveTextEdit->appendPlainText(tr("【") + date + tr(" ") + QDateTime::currentDateTime().time().toString() + tr("】"));
}
/**********************************************************/
bool MainWindow::slotTryCreateTcpServer()
{
mtcpServer = new TcpServer(this);
if(! mtcpServer->listen(lhAddr, lhPort))
{
return false;
QMessageBox::information(this, tr("错误"), tr("尝试建立服务器失败! 请确认网络状态和端口。"));
}
connect(mtcpServer, SIGNAL(updateTcpServer(char*, int, int)), this, SLOT(tcpServerDataReceived(char*, int, int)));
connect(this, SIGNAL(sendDataToClient(char*, int, int, int)), mtcpServer, SLOT(sendDataToClient(char*, int, int, int)));
connect(mtcpServer, SIGNAL(addClientLink(QString, int)), this, SLOT(addClientLink(QString, int)));
connect(mtcpServer, SIGNAL(removeClientLink(QString, int)), this, SLOT(removeClientLink(QString, int)));
return true;
}
/**********************************************************/
void MainWindow::slotDeleteTcpServer()
{
//disconnect(mtcpServer,SIGNAL(updateTcpServer(char*,int,int)),this,SLOT(tcpServerDataReceived(char*,int,int)));
mtcpServer->disconnect();
mtcpServer->close();
delete mtcpServer;
}
/**********************************************************/
void MainWindow::tcpServerDataReceived(char *msg, int length, int socketDescriptorEx)
{
if(ui->StartRcvFile->checkState()) { //保存接收数据到文件
if(curFile != 0) {
curFile->write(msg, length);
}
} else { //显示接收数据
if(!ui->cBox_PauseShowRcv->checkState()) {
int idx = tcpClientSocketDescriptorList.indexOf(socketDescriptorEx);
QString tmpIPPort = ui->cBoxClients->itemText(idx);
if(CurIPPort != tmpIPPort) {
CurIPPort = tmpIPPort;
if(ui->ReceiveTextEdit->toPlainText().size() != 0) {
ui->ReceiveTextEdit->insertPlainText("\n");
}
ui->ReceiveTextEdit->insertPlainText(tr("【数据来自") + CurIPPort + tr("】\n"));
}
//显示数据接收时间
if(ui->cBox_ShowRcvTime->checkState()) insertDateTimeInRcvDisp();
//输出数据到接收显示区
if(!ui->cBox_RcvHexDisp->checkState()) { //显示字符串
ui->ReceiveTextEdit->insertPlainText(msg);
} else { //显示十六进制字符串
for(int i = 0; i < length; i++) {
char ch = *(msg + i);
QString tmpStr = "";
tmpStr.append(toHex[(ch & 0xf0) / 16]);
tmpStr.append(toHex[ch & 0x0f]);
tmpStr.append(" ");
ui->ReceiveTextEdit->insertPlainText(tmpStr);
}
}
}
}
//群聊功能控制,转发数据
if(ui->cBox_chatMode->checkState()) {
if(ui->cBox_echoMode->checkState()) {
emit sendDataToClient(msg, length, 0, 0);
} else {
emit sendDataToClient(msg, length, 0, socketDescriptorEx);
}
}
//数据接收计数器更新
rcvDataCnt += length;
ui->lEdit_RcvCnt->setText(QString::number(rcvDataCnt, 10));
}
/**********************************************************/
void MainWindow::addClientLink(QString clientAddrPort, int socketDescriptor)
{
if(TcpClientLinkCnt == 0) {
tcpClientSocketDescriptorList.clear();
tcpClientSocketDescriptorList.append(0);
ui->cBoxClients->addItem(tr("全部连接"));
}
TcpClientLinkCnt++;
tcpClientSocketDescriptorList.append(socketDescriptor);
ui->cBoxClients->addItem(clientAddrPort);
}
/**********************************************************/
void MainWindow::removeClientLink(QString clientAddrPort, int socketDescriptor)
{
if(socketDescriptor != -1)
return;
if(TcpClientLinkCnt <= 1) {
tcpClientSocketDescriptorList.clear();
ui->cBoxClients->clear();
} else {
TcpClientLinkCnt--;
int idx = ui->cBoxClients->findText(clientAddrPort);
ui->cBoxClients->removeItem(idx);
tcpClientSocketDescriptorList.removeAt(idx);
}
}
/***********************************************/
//保存接收区的文本文件的内容到文件
void MainWindow::on_pBtnSaveRcvData_clicked()
{
QString path = QFileDialog::getSaveFileName(this, tr("保存接收区内容到文本文件"), tr(""), tr("文本文件(*.txt)"));
QFile saveFile(path);
if(saveFile.open(QFile::WriteOnly | QIODevice::Truncate)) {
QTextStream out(&saveFile);
QString str = ui->ReceiveTextEdit->toPlainText();
out << str;
}
saveFile.close();
}
/***********************************************/
//开启定时自动发送功能
void MainWindow::on_cBoxLoopSnd_toggled(bool checked)
{
if(checked) {
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(toSendData()));
int msInterval = ui->lEdit_Interval_ms->text().toInt();
if(msInterval > 0) {
timer->setInterval(ui->lEdit_Interval_ms->text().toInt());
} else {
ui->cBoxLoopSnd->setChecked(false);
delete timer;
}
} else {
timer->stop();
delete timer;
ui->pBtnSendData->setEnabled(true);
}
}
/***********************************************/
//修改发送间隔时间
void MainWindow::on_lEdit_Interval_ms_editingFinished()
{
int msInterval = ui->lEdit_Interval_ms->text().toInt();
if(msInterval > 0) {
timer->setInterval(ui->lEdit_Interval_ms->text().toInt());
}
}
/***********************************************/
//清空发送区
void MainWindow::on_pBtnClearSndDisp_clicked()
{
ui->tEditSendText->clear();
}
/***********************************************/
//载入文本文件到发送区
void MainWindow::on_pBtnLoadSndData_clicked()
{
QString path = QFileDialog::getOpenFileName(this, tr("载入文本文件到发送区"));
QFile file(path);
QByteArray str;
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QMessageBox::information(this, tr("错误"), tr("打开文件失败。"));
return ;
} else {
while(!file.atEnd()) {
str = file.readLine();
ui->tEditSendText->insertPlainText(str);
}
}
file.close();
}
/***********************************************/
//接收数据转存到文件
void MainWindow::on_StartRcvFile_clicked(bool checked)
{
if(checked) {
QFileDialog *qfd = new QFileDialog(this);
qfd->setViewMode(QFileDialog::List);
qfd->setFileMode(QFileDialog::AnyFile);
qfd->setWindowTitle(tr("建立接收文件"));
// qfd->setFilter(tr("所有文件(*.*)")); //qt4.8
qfd->setNameFilter(tr("所有文件(*.*)")); //qt5
if(qfd->exec() == QDialog::Accepted) //如果成功的执行
{
QStringList slist = qfd->selectedFiles();
CurPath = slist[0];
curFile = new QFile(CurPath);
if(!curFile->open(QFile::WriteOnly | QIODevice::Truncate)) {
//打开文件失败
ui->StartRcvFile->setChecked(false);
return;
}
ui->ReceiveTextEdit->setPlainText(tr("接收数据保存到文件:\n") + CurPath + "\n");
on_pBtnResetCnt_clicked();
} else {
ui->StartRcvFile->setChecked(false);
return;
}
} else {
ui->ReceiveTextEdit->clear();
if(curFile) curFile->close();
if(curFile) delete curFile;
}
}
/***********************************************/
//发送数据源为文件
void MainWindow::on_cBoxStartSndFile_clicked(bool checked)
{
if(checked) {
QFileDialog *qfd = new QFileDialog(this);
qfd->setViewMode(QFileDialog::List);
qfd->setFileMode(QFileDialog::AnyFile);
qfd->setWindowTitle(tr("选择发送文件"));
// qfd->setFilter(tr("所有文件(*.*)")); //qt4.8
qfd->setNameFilter(tr("所有文件(*.*)")); //qt5
if(qfd->exec() == QDialog::Accepted) //如果成功的执行
{
QStringList slist = qfd->selectedFiles();
CurPath = slist[0];
curFile = new QFile(CurPath);
if(!curFile->open(QFile::ReadOnly | QIODevice::Truncate)) {
//打开文件失败
ui->cBoxStartSndFile->setChecked(false);
return;
}
ui->ReceiveTextEdit->setPlainText(tr("从文件发送数据:\n") + CurPath + tr("\n"));
} else {
ui->cBoxStartSndFile->setChecked(false);
return;
}
} else {
ui->ReceiveTextEdit->clear();
if(curFile) curFile->close();
if(curFile) delete curFile;
}
}
/***********************************************/
//发送区以十六进制与字符串间切换
void MainWindow::on_cBox_SndHexDisp_clicked(bool checked)
{
QByteArray datagram;
if(checked) {
if(ui->tEditSendText->toPlainText().length() != 0) {
datagram = ui->tEditSendText->toPlainText().toLocal8Bit();
ui->tEditSendText->clear();
for(int i = 0; i < datagram.size(); i++) {
char ch = datagram.at(i);
QString tmpStr = QString::number(ch, 16);
ui->tEditSendText->insertPlainText(tmpStr + " ");
}
}
} else {
if(ui->tEditSendText->toPlainText().length() != 0) {
QStringList hexStr = ui->tEditSendText->toPlainText().split(" ", QString::SkipEmptyParts);
int hexSize = hexStr.size();
qDebug() << QString::number(hexSize, 10);
for(int i = 0; i < hexSize; i++) {
QString hexSubStr = hexStr.at(i);
datagram.append(ConvertHexStr(hexSubStr));
}
ui->tEditSendText->clear();
QString msg = datagram.data();
ui->tEditSendText->setPlainText(msg);
}
}
}
/***********************************************/
//转化十六进制中的字符到ASCII
char MainWindow::ConvertHexChar(char ch)
{
if((ch >= '0') && (ch <= '9'))
return ch - 0x30;
else if((ch >= 'A') && (ch <= 'F'))
return ch - 'A' + 10;
else if((ch >= 'a') && (ch <= 'f'))
return ch - 'a' + 10;
else return (-1);
}
/***********************************************/
//转化十六进制字符到ASCII字母
char MainWindow::ConvertHexStr(QString hexSubStr)
{
char ch = 0;
if(hexSubStr.length() == 2) {
// ch = ConvertHexChar(hexSubStr.at(0).toAscii())*16+ ConvertHexChar(hexSubStr.at(1).toAscii()); //qt4.8
ch = ConvertHexChar(hexSubStr.at(0).toLatin1()) * 16 + ConvertHexChar(hexSubStr.at(1).toLatin1());
} else if(hexSubStr.length() == 1) {
//ch = ConvertHexChar(hexSubStr.at(0).toAscii()); //qt4.8
ch = ConvertHexChar(hexSubStr.at(0).toLatin1());
}
return ch;
}
/***********************************************/
//毫秒级延时
void MainWindow::msDelay(unsigned int msec)
{
QTime dieTime = QTime::currentTime().addMSecs(msec);
while(QTime::currentTime() < dieTime)
QCoreApplication::processEvents(QEventLoop::AllEvents, 1);
}
void MainWindow::on_actionEnglish_triggered()
{
translator.load(":/language/English.qm");
qApp->installTranslator(&translator);
ui->retranslateUi(this);
}
void MainWindow::on_actionChinese_triggered()
{
translator.load(":/language/Chinese.qm");
qApp->installTranslator(&translator);
ui->retranslateUi(this);
}