一个小工具,上次没有存又重装了系统,又得重写了一份。
.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include<QTcpServer>
#include<QTcpSocket>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
QTcpServer * myserver;
QTcpSocket * m_tcpSocket;
QByteArray QString2Hex(QString str);
char ConvertHexChar(char ch);
private slots:
void newConnect();
void readMessage();
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
myserver=new QTcpServer(this);
myserver->listen(QHostAddress::Any,9952); //监听任何连上19999端口的ip
connect(myserver,SIGNAL(newConnection()),this,SLOT(newConnect())); //新连接信号触发,调用newConnect()槽函数,这个跟信号函数一样,其实你可以随便取。
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::newConnect()
{
m_tcpSocket = myserver->nextPendingConnection(); //得到每个连进来的socket
connect(m_tcpSocket,SIGNAL(readyRead()),this,SLOT(readMessage())); //有可读的信息,触发读函数槽
}
void MainWindow::readMessage() //读取信息
{
// ui->textEdit_rec->te
QByteArray qba= m_tcpSocket->readAll(); //读取
while (m_tcpSocket->waitForReadyRead(10)) {
qba+=m_tcpSocket->readAll();
}
qDebug()<<qba;
QString ss=QVariant(qba).toString();
ui->textEdit->append(qba.toHex());
}
void MainWindow::on_pushButton_clicked()
{
QString strMesg= ui->lineEdit->text();
ui->textEdit->append(strMesg);
qDebug()<<strMesg;
QByteArray tmp=QString2Hex(strMesg);
//19 B2 00 00 00 06 01 03 00 01 00 08
m_tcpSocket->write(tmp); //发送
}
QByteArray MainWindow::QString2Hex(QString str)
{
QByteArray senddata;
int hexdata,lowhexdata;
int hexdatalen = 0;
int len = str.length();
senddata.resize(len/2);
char lstr,hstr;
for(int i=0; i<len; )
{
hstr=str[i].toLatin1();
if(hstr == ' ')
{
i++;
continue;
}
i++;
if(i >= len)
break;
lstr = str[i].toLatin1();
hexdata = ConvertHexChar(hstr);
lowhexdata = ConvertHexChar(lstr);
if((hexdata == 16) || (lowhexdata == 16))
break;
else
hexdata = hexdata*16+lowhexdata;
i++;
senddata[hexdatalen] = (char)hexdata;
hexdatalen++;
}
senddata.resize(hexdatalen);
return senddata;
}
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);
}
|