您的位置:首页 > 理论基础 > 计算机网络

Qt中的TCP通信

2017-07-22 13:32 316 查看
简述

    Qt的TCP通信类在network模块中。主要使用了两个类 QTcpServer和QTcpSocket。它们封装个不同操作系统的通信套接字,使用起来也一样。

      QTcpServer:主要用在服务端,用来监听客户端的连接请求。有两个常用的接口

           newConnection():                这个是一个信号,当QTcpServer检测到有客户端连接时会发出。

           nextPendingConnection();     用于获取已经和客户端连接成功后的套接字QTcpSocket,主要用于和客户端通信。

      QTcpSocket:                            主要用两端的互相通信,常用的接口

          readAll();                                  从QTcpSocket读取数据

          write();                                     向QTcpSocket写数据

          disconnectFromHost();          
断开连接

实现    Qt4.8





服务端:

serverwid.h

#ifndef SERVERWID_H
#define SERVERWID_H

#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QPushButton>
#include <QTextEdit>

namespace Ui {
class ServerWid;
}

class ServerWid : public QWidget
{
Q_OBJECT

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

void initWidget();

private slots:
void getTcpSocket();
void sendData();
void ReceData();

void CloseWid();
private:
Ui::ServerWid *ui;

QTcpServer *m_TcpServer;
QTcpSocket *m_TcpSocket;

QPushButton *m_SendButton;
QPushButton *m_CloseButton;

QTextEdit *m_SendText;
QTextEdit *m_ReceText;
};

#endif // SERVERWID_H

serverwid.cpp

#include "serverwid.h"
#include "ui_serverwid.h"

#include <QDebug>
#include <QWidget>
#include <QHBoxLayout>
#include <QVBoxLayout>

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

initWidget();

//监听套接字
m_TcpServer = new QTcpServer(this);
m_TcpServer->listen(QHostAddress::Any, 5555);

m_TcpSocket = NULL;
//监听客户端连接信号槽
connect(m_TcpServer, SIGNAL(newConnection()), this, SLOT(getTcpSocket()));

//发送按钮信号槽
connect(m_SendButton, SIGNAL(pressed()), this, SLOT(sendData()));
//关闭按钮信号槽
connect(m_CloseButton, SIGNAL(pressed()), this, SLOT(CloseWid()));
}

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

//界面初始化
void ServerWid::initWidget()
{
this->resize(800,600);
this->setWindowTitle("ServerWidget");

QVBoxLayout *VLayoutText = new QVBoxLayout(this);
VLayoutText->setMargin(8);
QWidget *TextWidget = new QWidget(this);
TextWidget->setLayout(VLayoutText);
m_ReceText = new QTextEdit(TextWidget);
m_ReceText->setReadOnly(true);
m_SendText = new QTextEdit(TextWidget);
m_SendText->setMaximumHeight(100);
VLayoutText->addWidget(m_ReceText);
VLayoutText->addWidget(m_SendText);

QHBoxLayout *HLayoutButton = new QHBoxLayout(this);
HLayoutButton->setMargin(8);
QWidget *ButtonWidget = new QWidget(this);
ButtonWidget->setLayout(HLayoutButton);
m_SendButton = new QPushButton(this);
m_SendButton->setText(QString("Send").toUtf8().data());
m_CloseButton = new QPushButton(this);
m_CloseButton->setText(QString("Close").toUtf8().data());
HLayoutButton->addWidget(m_SendButton);
HLayoutButton->addStretch();
HLayoutButton->addWidget(m_CloseButton);

QVBoxLayout *VLayoutMain = new QVBoxLayout(this);
VLayoutMain->setMargin(2);
this->setLayout(VLayoutMain);
VLayoutMain->addWidget(TextWidget);
VLayoutMain->addWidget(ButtonWidget);
}

//取出建立好链接的套接字
void ServerWid::getTcpSocket()
{
m_TcpSocket = m_TcpServer->nextPendingConnection();
//接收客户端数据信号槽
connect(m_TcpSocket, SIGNAL(readyRead()), this, SLOT(ReceData()));

//获取对方的ip和端口
QString ip = m_TcpSocket->peerAddress().toString();
qint16 port = m_TcpSocket->peerPort();

QString temp = QString("have a client succeed connect! ip:%1 port:%2").arg(ip).arg(port);
m_ReceText->append(temp);

}

//发送数据
void ServerWid::sendData()
{
QString str = m_SendText->toPlainText();

if(m_TcpSocket != NULL)
{
m_SendText->clear();
m_TcpSocket->write(str.toUtf8().data());
}

}

//接收数据
void ServerWid::ReceData()
{
QByteArray strArr = m_TcpSocket->readAll();
m_ReceText->append(strArr);
}

//关闭连接
void ServerWid::CloseWid()
{
if(m_TcpSocket != NULL)
{
m_TcpSocket->disconnectFromHost();
m_TcpSocket->close();

m_TcpSocket = NULL;
}
}客户端:

clientwid.h

#ifndef CLIENTWID_H
#define CLIENTWID_H

#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QPushButton>
#include <QTextEdit>

namespace Ui {
class ClientWid;
}

class ClientWid : public QWidget
{
Q_OBJECT

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

void initWidget();

private slots:
void sendData();
void ReceData();

void CloseWid();
void ConnenctServer();

private:
Ui::ClientWid *ui;

QPushButton *m
cae2
_SendButton;
QPushButton *m_ConneButton;
QPushButton *m_CloseButton;

QTextEdit *m_SendText;
QTextEdit *m_ReceText;

QTcpSocket *m_ClientTcpSocket;
};

#endif // CLIENTWID_H

clientwid.cpp

#include "clientwid.h"
#include "ui_clientwid.h"

#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QDebug>

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

initWidget();

m_ClientTcpSocket = new QTcpSocket(this);

connect(m_ConneButton, SIGNAL(pressed()), this, SLOT(ConnenctServer()));
connect(m_SendButton, SIGNAL(pressed()), this, SLOT(sendData()));
connect(m_ClientTcpSocket, SIGNAL(readyRead()), this, SLOT(ReceData()));
connect(m_CloseButton, SIGNAL(pressed()), this, SLOT(CloseWid()));
}

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

void ClientWid::ConnenctServer()
{
m_ClientTcpSocket->connectToHost(QHostAddress("127.0.0.1"), QString("5555").toInt());
QString temp = QString("succeed Server connect");
m_ReceText->append(temp);
}

void ClientWid::sendData()
{
QString sendStr = m_SendText->toPlainText();
m_SendText->clear();

m_ClientTcpSocket->write(sendStr.toUtf8().data());
}

void ClientWid::ReceData()
{
QByteArray strArr = m_ClientTcpSocket->readAll();
m_ReceText->append(strArr);
}

//关闭连接
void ClientWid::CloseWid()
{
m_ClientTcpSocket->disconnectFromHost();
m_ClientTcpSocket->close();

QString temp = QString("Disconnects from the server");
m_ReceText->append(temp);
}

void ClientWid::initWidget()
{
this->resize(800,600);
this->setWindowTitle("ClientWidget");

QVBoxLayout *VLayoutText = new QVBoxLayout(this);
VLayoutText->setMargin(8);
QWidget *TextWidget = new QWidget(this);
TextWidget->setLayout(VLayoutText);
m_ReceText = new QTextEdit(TextWidget);
m_ReceText->setReadOnly(true);
m_SendText = new QTextEdit(TextWidget);
m_SendText->setMaximumHeight(100);
VLayoutText->addWidget(m_ReceText);
VLayoutText->addWidget(m_SendText);

QHBoxLayout *HLayoutButton = new QHBoxLayout(this);
HLayoutButton->setMargin(8);
QWidget *ButtonWidget = new QWidget(this);
ButtonWidget->setLayout(HLayoutButton);
m_SendButton = new QPushButton(this);
m_SendButton->setText(QString("Send").toUtf8().data());
m_ConneButton = new QPushButton(this);
m_ConneButton->setText(QString("Conne").toUtf8().data());
m_CloseButton = new QPushButton(this);
m_CloseButton->setText(QString("Close").toUtf8().data());
HLayoutButton->addWidget(m_SendButton);
HLayoutButton->addStretch();
HLayoutButton->addWidget(m_ConneButton);
HLayoutButton->addStretch();
HLayoutButton->addWidget(m_CloseButton);

QVBoxLayout *VLayoutMain = new QVBoxLayout(this);
VLayoutMain->setMargin(2);
this->setLayout(VLayoutMain);
VLayoutMain->addWidget(TextWidget);
VLayoutMain->addWidget(ButtonWidget);
}

main函数

#include <QApplication>
#include <QTextCodec>
#include "clientwid.h"
#include "serverwid.h"

int main(int argc, char *argv[])
{
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForLocale(codec);
QTextCodec *BianMa = QTextCodec::codecForName("GBK");
QTextCodec::setCodecForLocale(BianMa);

QApplication a(argc, argv);

//服务端
ServerWid w;
w.show();
//客户端
ClientWid cw;
cw.show();

return a.exec();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Qt 通信 TCP C++