qt tcp socket简单的通信程序

本文介绍了如何使用QT库创建TCP Socket通信程序,包括客户端和服务器端的实现。客户端通过QTcpSocket连接到服务器,并在按钮触发时发送LineEdit中的文本。服务器端通过QTcpServer监听连接,接收到客户端消息后显示在界面上。
摘要由CSDN通过智能技术生成
  1. socket通信分为server端与client端,基于tcp的需要首先建立server-client的连接,然后才能通信。
  2. 客户端程序如下:
  3. 在QT上建立一个widget界面程序,在界面中添加一个button和LineEdite,分别命名为sendButton、inputLine;LineEdit是客户端输入,点击button发送输入内容。
  4. 在工程文件中加入 QT +=network
  5. 客户端的mywidget.h
  6. #ifndef MYWIDGET_H
    #define MYWIDGET_H


    #include <QWidget>
    #include <QtNetwork>


    namespace Ui {
    class myWidget;
    }


    class myWidget : public QWidget
    {
        Q_OBJECT
        
    public:
        explicit myWidget(QWidget *parent = 0);
        ~myWidget();
        
    private:
        Ui::myWidget *ui;
        QTcpSocket *client;
        const char *data;
    private slots:
        void senddata();
    };


    #endif // MYWIDGET_H
  7. 客户端的mywidget.cpp
  8. :#include "mywidget.h"
    #include "ui_mywidget.h"


    myWidget::myWidget(QWidget *parent) :
        QWidget(parent),
        ui(new Ui::myWidget)
    {
        ui->setupUi(this);
        client = new QTcpSocket(this);
        client->connectToHost(QHostAddress("10.9.3.95"),5000);
        connect(ui->sendButton,SIGNAL(clicked()),this,SLOT(senddata()));
    }


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


    void myWidget::senddata()
    {
        data=ui->inputLine->text().toStdString().c_str();
        client->write(data);
        ui->inputLine->setText("send ok!");
    }
  9. 服务端:服务端本程序中只用来接收客户端发送来的消息,在server的界面中添加一个label用来提示是否有客户端连接;添加一个LineEdit用来输出服务端接收到的
  10. 消息。在工程中添加QT  +=network
  11. 服务端程序:


  12. #ifndef MYWIDGET_H
    #define MYWIDGET_H


    #include <QWidget>
    #include <QTcpServer>
    #include <QTcpSocket>


    namespace Ui {
    class mywidget;
    }


    class mywidget : public QWidget
    {
        Q_OBJECT
        
    public:
        explicit mywidget(QWidget *parent = 0);
        ~mywidget();
        
    private:
        Ui::mywidget *ui;
        QTcpServer *server;
        QTcpSocket *clientConnection;
        char recbuf[1024];
    private slots:
        void acceptConnection();
        void readClient();
    };


    #endif // MYWIDGET_H
  13. #include "mywidget.h"
    #include "ui_mywidget.h"


    mywidget::mywidget(QWidget *parent) :
        QWidget(parent),
        ui(new Ui::mywidget)
    {
        ui->setupUi(this);
        server=new QTcpServer();
        clientConnection=new QTcpSocket();
        server->listen(QHostAddress::Any,5000);
        connect(server,SIGNAL(newConnection()),this,SLOT(acceptConnection()));




    }


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


    void mywidget::acceptConnection()
    {
        clientConnection=server->nextPendingConnection();
        ui->label->setText("connect....");
        connect(clientConnection,SIGNAL(readyRead()),this,SLOT(readClient()));
    }


    void mywidget::readClient()
    {
        memset(recbuf,0,sizeof(recbuf));
        clientConnection->read(recbuf,1024);
        ui->recLine->clear();
        ui->recLine->setText(recbuf);


    }
Qt TCP套接字通信实例通常用于客户端和服务器之间的双向数据传输,例如聊天应用、游戏服务器等。以下是使用Qt C++的一个简单示例: 首先,你需要包含必要的头文件并设置基本的TCP服务器: ```cpp #include <QObject> #include <QTcpServer> #include <QTcpSocket> class Server : public QObject { Q_OBJECT public slots: void startServer() { QTcpServer *server = new QTcpServer(this); if (server->listen(QHostAddress::Any, 8080)) { // 监听所有地址的8080端口 while (!server->isListening()) { // 当服务器开始监听时 qApp->processEvents(); // 保持应用程序活跃 } connect(server, &QTcpServer::newConnection, this, &Server::handleNewConnection); // 连接到新连接事件 qDebug() << "Server is listening on port 8080"; } else { qDebug() << "Failed to listen on port 8080"; } } private slots: void handleNewConnection() { QTcpSocket *socket = server->nextPendingConnection(); connect(socket, &QTcpSocket::readyRead, this, &Server::handleDataReceived); connect(socket, &QObject::destroyed, this, &Server::removeSocket); } void handleDataReceived() { QByteArray data = socket->readAll(); emit sendDataToClient(data); // 发送给处理数据的部分 } void removeSocket(QObject *sender) { delete sender; // 删除已断开的连接 } }; ``` 然后,你可以创建一个`Client`类,进行相应的TCP连接请求: ```cpp class Client : public QObject { Q_OBJECT public: explicit Client(QObject *parent = nullptr) : QObject(parent), socket(new QTcpSocket(this)) {} public slots: void connectToServer(const QString &host, quint16 port) { socket->connectToHost(host, port); connect(socket, &QTcpSocket::connected, this, &Client::sendHelloMessage); connect(socket, &QTcpSocket::error, this, &Client::connectionError); } private slots: void sendHelloMessage() { socket->write("Hello from client!"); // 发送一条消息到服务器 } void connectionError() { qDebug() << "Connection error"; } signals: void receiveDataFromServer(const QByteArray &data); // 信号发射接收的数据 protected: QTcpSocket *socket; }; ``` 要在客户端和服务器之间传递数据,需要在`Server`类中添加信号处理器,并在`Client`类中对接收的信号作出响应: ```cpp void Server::sendDataToClient(const QByteArray &data) { emit sendDataToClient(data); // 发送给客户端的信号 } void Client::receiveDataFromServer(const QByteArray &data) { qDebug() << "Received message: " << data.toUtf8().constData(); } ``` 最后,在主程序中初始化服务器和客户端: ```cpp int main(int argc, char *argv[]) { QApplication app(argc, argv); Server server; connect(&app, &QApplication::aboutToQuit, &server, &Server::quit); // 关闭服务器时关闭应用 server.startServer(); Client client; client.connectToServer("localhost", 8080); // 如果是本地测试,主机名通常为"localhost" return app.exec(); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值