1、简介
本次通过与上文:QT网络通信-服务器(一)类似设计一个客户端界面,实现与服务器进行通讯。
2、界面
3、widget.h
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QWidget> #include <QTcpServer> #include <QTcpSocket> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = nullptr); ~Widget(); //QTcpServer *tcpserver;//声明一个QTcpserver的对象,用于监听 QTcpSocket *tcpsocket;//创建服务器的套接字,用于与客户端进行通信 private slots: void on_open_Button_clicked(); void on_close_Button_clicked(); void on_send_Button_clicked(); void connected_Slot(); void readyRead_Slot(); private: Ui::Widget *ui; }; #endif // WIDGET_H
4、widget.c
#include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); //tcpserver = new QTcpServer(this); tcpsocket = new QTcpSocket(this); } Widget::~Widget() { delete ui; } //client端的连接服务器按钮 void Widget::on_open_Button_clicked() { // 根据输入的ip和port连接指定的服务器 tcpsocket->connectToHost(ui->IP_line->text(),ui->port_line->text().toUShort()); connect(tcpsocket,SIGNAL(connected()),this,SLOT(connected_Slot())); } void Widget::connected_Slot() { connect(tcpsocket,SIGNAL(readyRead()),this,SLOT(readyRead_Slot())); } void Widget::readyRead_Slot() { ui->rece_TextEdit->appendPlainText(tcpsocket->readAll()); } void Widget::on_close_Button_clicked() { tcpsocket->close(); } void Widget::on_send_Button_clicked() { tcpsocket->write(ui->send_line->text().toLocal8Bit().data()); }