码迷,mamicode.com
首页 > 其他好文 > 详细

QT TCP通信收发数据

时间:2018-07-12 17:58:33      阅读:999      评论:0      收藏:0      [点我收藏+]

标签:button   oid   client   list   tcp通信   localhost   .data   res   连接服务器   

首先在工程文件.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通信收发数据

标签:button   oid   client   list   tcp通信   localhost   .data   res   连接服务器   

原文地址:https://www.cnblogs.com/wxh-53919/p/9300371.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!