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);


 

实现代码

 1 tcpServer::tcpServer(QWidget *parent) :
 2     QDialog(parent),
 3     ui(new Ui::tcpServer)
 4 {
 5     ui->setupUi(this);
 6     mServer = new QTcpServer();
 7     //关联客户端连接信号newConnection
 8     connect(mServer,SIGNAL(newConnection()),this,SLOT(new_client())); //连接客户端
 9     //启动服务器监听
10     mServer->listen(QHostAddress::Any,1122);
11 }
12 tcpServer::~tcpServer()
13 {
14     delete ui;
15 }
16 void tcpServer::new_client()
17 {
18      mSocket = mServer->nextPendingConnection();//与客户端通信的套接字
19      //关联接收客户端数据信号readyRead信号(客户端有数据就会发readyRead信号)
20      connect(mSocket,SIGNAL(readyRead()),this,SLOT(read_client_data()));
21  }
22 void tcpServer::read_client_data()
23 {
24      //可以实现同时读取多个客户端发送过来的消息
25      QTcpSocket *obj = (QTcpSocket*)sender();
26      QByteArray msg = obj->readAll();
27      unsigned short size = msg.size();
28      unsigned char msg1[10] = {0};
29      memcpy(msg1, msg.data(), size);
30      qDebug()<<msg1[0]<<msg1[1]<<msg1[2]<<msg1[3];
31 }
32  
33 void tcpServer::on_pushButton_clicked()
34 {
35     unsigned char msg[10];
36     msg[0]='*';
37     msg[1]=10;
38     msg[2]=30;
39     msg[4]=1;
40     mSocket->write((char*)msg,5);
41 }

 


客户端

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);


 

实现代码

 1 tcpClick::tcpClick(QWidget *parent) :
 2     QWidget(parent),
 3     ui(new Ui::tcpClick)
 4 {
 5     ui->setupUi(this);
 6     mSocket = new QTcpSocket();
 7    //关联数据信号
 8    connect(mSocket,SIGNAL(readyRead()),this,SLOT(read_data()));
 9   //连接服务器,设置ip和端口号
10     mSocket->connectToHost(QHostAddress::LocalHost,1122);
11 }
12 tcpClick::~tcpClick()
13 {
14     delete ui;
15 }
16 void tcpClick::read_data()
17 {
18     QByteArray msg = mSocket->readAll();
19     unsigned short size = msg.size();
20     unsigned char msg1[10] = {0};
21     memcpy(msg1, msg.data(), size);
22     qDebug()<<msg1[0]<<msg1[1]<<msg1[2]<<msg1[3];
23 }
24  
25 void tcpClick::on_pushButton_clicked()
26 {
27     unsigned char msg[10];
28     msg[0]='*';
29     msg[1]=30;
30     msg[2]=20;
31     msg[4]=11;
32     mSocket->write((char*)msg,5);
33 }

 

posted on 2018-07-12 16:54  小小小哈  阅读(13310)  评论(0编辑  收藏  举报

导航