马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
TCP客户端
Widget.h
- #ifndef WIDGET_H
- #define WIDGET_H
- #include <QWidget>
- #include <QTcpSocket> //客户端类
- #include <QMessageBox>
- #include <QListWidgetItem>
- #include <QDebug>
- QT_BEGIN_NAMESPACE
- namespace Ui { class Widget; }
- QT_END_NAMESPACE
- class Widget : public QWidget
- {
- Q_OBJECT
- public:
- Widget(QWidget *parent = nullptr);
- ~Widget();
- public slots:
- void connected_slot();//connected信号对应槽函数的声明
- void readyRead_slot();
- void disconnected_slot();
- private slots:
- void on_connectbtn_clicked();
- void on_sendbtn_clicked();
- void on_disconnectbtn_clicked();
- private:
- Ui::Widget *ui;
- QString msgfor="";
- //实例化一个客户端指针
- QTcpSocket *socket;
- //定义一个变量存储用户名
- QString userName;
- };
- #endif // WIDGET_H
复制代码 Widget.cpp
- #include "widget.h"
- #include "ui_widget.h"
- #include <string>
- #include<iostream>
- Widget::Widget(QWidget *parent)
- : QWidget(parent)
- , ui(new Ui::Widget)
- ,socket(new QTcpSocket(this))//给客户端实例化空间
- {
- ui->setupUi(this);
- //初始化界面,设置为不可用
- ui->msgEdit->setEnabled(false);
- ui->sendbtn->setEnabled(false);
- ui->disconnectbtn->setEnabled(false);
- //如果成功连接服务器,那么客户端就会自动发射一个connected()信号
- //将该信号连接到自定义的槽函数,书写逻辑代码。由于只需要连接一次,所以连接函数写在构造函数中
- connect(socket, &QTcpSocket::connected, this, &Widget::connected_slot);
- //此时说明客户端和服务器已经成功建立连接,如果服务器发来数据,那么客户端就会自动发射readyRead()信号
- //将该信号连接到自定义的槽函数中,读取数据。由于只需要连接一次,所以连接函数写在构造函数中
- connect(socket, &QTc
复制代码 |