QT TCP通信收发数据

Posted wxh-53919

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了QT TCP通信收发数据相关的知识,希望对你有一定的参考价值。

首先在工程文件.pro中加入

QT       += network

需要加的头文件

#include <QTcpServer>
#include <QTcpSocket>


 

服务端

1.创建初始化对象

mServer = new QTcpServer();

mSocket = new QTcpSocket();

2.关联客户端

connect(mServer,SIGNAL(newConnection()),this,SLOT(new_client()));

3.启动监听服务

mServer->listen(QHostAddress::Any,1122);

4.接受数据

mSocket = mServer->nextPendingConnection();//与客户端通信的套接字

connect(mSocket,SIGNAL(readyRead()),this,SLOT(read_client_data()));

5.发送数据

mSocket->write((char*)msg,5);


 

实现代码

tcpServer::tcpServer(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::tcpServer)
{
    ui->setupUi(this);
    mServer = new QTcpServer();
    //关联客户端连接信号newConnection
    connect(mServer,SIGNAL(newConnection()),this,SLOT(new_client())); //连接客户端
    //启动服务器监听
    mServer->listen(QHostAddress::Any,1122);
}
tcpServer::~tcpServer()
{
    delete ui;
}
void tcpServer::new_client()
{
     mSocket = mServer->nextPendingConnection();//与客户端通信的套接字
     //关联接收客户端数据信号readyRead信号(客户端有数据就会发readyRead信号)
     connect(mSocket,SIGNAL(readyRead()),this,SLOT(read_client_data()));
 }
void tcpServer::read_client_data()
{
     //可以实现同时读取多个客户端发送过来的消息
     QTcpSocket *obj = (QTcpSocket*)sender();
     QByteArray msg = obj->readAll();
     unsigned short size = msg.size();
     unsigned char msg1[10] = {0};
     memcpy(msg1, msg.data(), size);
     qDebug()<<msg1[0]<<msg1[1]<<msg1[2]<<msg1[3];
}
 
void tcpServer::on_pushButton_clicked()
{
    unsigned char msg[10];
    msg[0]=‘*‘;
    msg[1]=10;
    msg[2]=30;
    msg[4]=1;
    mSocket->write((char*)msg,5);
}

客户端

1.创建初始化

mSocket = new QTcpSocket();

2.连接服务器,设置IP和端口

mSocket->connectToHost(QHostAddress::LocalHost,1122);

3.接收数据

connect(mSocket,SIGNAL(readyRead()),this,SLOT(read_data()));

QByteArray msg = mSocket->readAll();

4.发送数据

mSocket->write((char*)msg,5);


 

实现代码

tcpClick::tcpClick(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::tcpClick)
{
    ui->setupUi(this);
    mSocket = new QTcpSocket();
   //关联数据信号
   connect(mSocket,SIGNAL(readyRead()),this,SLOT(read_data()));
  //连接服务器,设置ip和端口号
    mSocket->connectToHost(QHostAddress::LocalHost,9988);
}
tcpClick::~tcpClick()
{
    delete ui;
}
void tcpClick::read_data()
{
    QByteArray msg = mSocket->readAll();
    unsigned short size = msg.size();
    unsigned char msg1[10] = {0};
    memcpy(msg1, msg.data(), size);
    qDebug()<<msg1[0]<<msg1[1]<<msg1[2]<<msg1[3];
}
 
void tcpClick::on_pushButton_clicked()
{
    unsigned char msg[10];
    msg[0]=‘*‘;
    msg[1]=30;
    msg[2]=20;
    msg[4]=11;
    mSocket->write((char*)msg,5);
}





























































以上是关于QT TCP通信收发数据的主要内容,如果未能解决你的问题,请参考以下文章

网络通信——TCP协议了解TCP协议的数据收发机制吗?说说收发阶段有哪些功能会导致延时

python中基于tcp协议的通信(数据传输)

基于QT的TCP通信服务

tcp通信

tcp通信

QT创建TCP Socket通信