您的位置:首页 > 编程语言 > Qt开发

【Y忍冬草】Qt之客户端实现数据的接收和发送

2018-01-12 11:12 501 查看




在使用通信功能时,需要在.pro工程中添加QT += network

相关代码:

tcpClient.h文件:

#ifndef TCPCLIENT_H
#define TCPCLIENT_H

#include <QWidget>
#include <QtNetwork>

namespace Ui {
class TcpClient;
}

class TcpClient : public QWidget
{
Q_OBJECT

public:
explicit TcpClient(QWidget *parent = 0);
~TcpClient();

private slots:
void NewConnect();  // 连接服务器
void ReadMessage(); // 接收数据
void SendMessage(); // 发送数据
void DisplayError(QAbstractSocket::SocketError); // 显示错误

void on_connectBtn_clicked();

private:
Ui::TcpClient *ui;

QTcpSocket *c_tcpSocket;
QString     c_readMsg;   // 存放从服务器接收到的字符串
QString     c_sendMsg;   // 存放发送给服务器的字符串
};

#endif // TCPCLIENT_H


tcpClient.cpp文件:

#include "tcpclient.h"
#include "ui_tcpclient.h"
#include <QMessageBox>

TcpClient::TcpClient(QWidget *parent) :
QWidget(parent),
ui(new Ui::TcpClient)
{
ui->setupUi(this);

c_tcpSocket = new QTcpSocket(this);

// 信号和槽的连接
connect(c_tcpSocket, SIGNAL(readyRead()), this, SLOT(ReadMessage()));
connect(c_tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(DisplayError(QAbstractSocket::SocketError)));
//    connect(c_tcpSocket, SIGNAL(connected()), this, SLOT(SendMessage()));
connect(ui->sendBtn, SIGNAL(clicked()), this, SLOT(SendMessage()));
}

TcpClient::~TcpClient()
{
delete ui;
}

void TcpClient::NewConnect()
{
c_tcpSocket->abort(); // 取消已有的连接
c_tcpSocket->connectToHost("192.168.1.111", 60000); // 连接到服务器
if (c_tcpSocket->waitForConnected(5000))
{
//        QString str = QString::fromLocal8Bit("通信成功!\n");
ui->readMsg->setText(tr("通信成功!\n"));
}
else
{
//        QString::fromLocal8Bit("通信失败!")
QMessageBox::critical(this, "Client", tr("通信失败!"));
}
}

void TcpClient::ReadMessage()
{
// 读取数据
while (c_tcpSocket->bytesAvailable() > 0)
{
QByteArray inBlock;
// 设置数据大小为读取的数据大小
inBlock.resize(c_tcpSocket->bytesAvailable());
c_tcpSocket->read(inBlock.data(), inBlock.size());

c_readMsg = QString(inBlock);

// 显示接收到的数据
ui->readMsg->setText(c_readMsg);
}
}

void TcpClient::SendMessage()
{
c_sendMsg = ui->sendMsg->text();

// 发送数据
c_tcpSocket->write(c_sendMsg.toLatin1(), c_sendMsg.length());
c_tcpSocket->waitForBytesWritten();

ui->sendMsg->clear();
}

void TcpClient::DisplayError(QAbstractSocket::SocketError)
{
// 输出错误信息
QString str = c_tcpSocket->errorString();
ui->errorMsg->setText(str);

c_tcpSocket->close();
}

// 连接按钮
void TcpClient::on_connectBtn_clicked()
{
NewConnect(); // 请求连接
}


相关下载:

http://download.csdn.net/download/y363703390/10202019
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Qt Client 收发数据