完整下载链接:gitee
https://gitee.com/HGSheng/qt-tcp-single-point-class
客户端
my_client::my_client(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::my_client)
{
ui->setupUi(this);
//1.申请内存
this->myclient = new QTcpSocket(this);
//2.关联连接成功信号
connect(this->myclient, SIGNAL(connected()), this, SLOT(connect_success()));
//3.关联数据接收信号
connect(this->myclient, SIGNAL(readyRead()), this, SLOT(receive_data()));
//4.连接服务器
QString ip = "192.168.16.143";
QString port = "1688";
this->myclient->connectToHost(QHostAddress(ip),port.toUShort());
}
my_client::~my_client()
{
delete ui;
}
//连接成功槽函数
void my_client::connect_success()
{
qDebug()<<"连接成功";
QString msg = "你好,我是客户端";
//发生数据
if(!msg.isEmpty())
this->myclient->write(msg.toUtf8());
}
//数据接收槽函数
void my_client::receive_data()
{
QString msg = this->myclient->readAll();
qDebug()<<"客户端有数据可读, 数据是 "<<msg;
}
服务器端
myserver::myserver(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::myserver)
{
ui->setupUi(this);
//1.分配内存
this->server = new QTcpServer(this);
//2.监听
this->server->listen(QHostAddress::Any, 1688);
//3.关联链接请求信号,如有连接则跳到自定义槽函数
QObject::connect(this->server, SIGNAL(newConnection()), this, SLOT(new_connect()));
}
myserver::~myserver()
{
delete ui;
}
//新连接槽函数
void myserver::new_connect()
{
QString port, ip, ip_port;
//1.通信套接字内存申请
this->client = new QTcpSocket(this);;
//2.新连接
this->client = this->server->nextPendingConnection();
//3.获取客户端IP及端口号
ip = this->client->peerAddress().toString();
port = QString::number(this->client->peerPort());
ip_port = ip + ":" + port;
ip_port = ip_port.remove(0, 7);//客户端IP及端口号
qDebug()<<"有新连接 地址信息是"<<ip_port;
//4.绑定信息接收信号机槽函数,如有信息发来则跳到自定义槽函数
QObject::connect(this->client, SIGNAL(readyRead()),this,SLOT(receive_data()));
//5.给客户端发送数据
QString msg = "你好,我是服务器端";
this->client->write(msg.toUtf8());
}
//数据接收槽函数
void myserver::receive_data()
{
QString msg = this->client->readAll();
qDebug()<<"服务器有数据可读, 数据是 "<<msg;
}