自制客户端与服务器通信

该代码示例展示了如何使用Qt库中的QTcpServer和QTcpSocket组件创建一个简单的TCP服务器和客户端。服务器监听8887端口,当有新的连接时,会显示连接信息。客户端可以连接到服务器并发送消息,服务器接收到消息后显示在界面上。
摘要由CSDN通过智能技术生成
服务器头文件
#ifndef DIALOG_H
#define DIALOG_H

#include <QtWidgets>
// 网络相关类
#include <QTcpServer>
#include <QTcpSocket>
#include <QTextStream>
#include <QDateTime>

namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

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

private:
    Ui::Dialog *ui;
    QTcpServer *server; // 服务器对象
    void showMessage(QString);// 给QTextBrowser设置显示信息的函数
    QTcpSocket *socket=NULL;
private slots:
    void newConnectionSlot();// 新连接来了的槽函数
    void disconnectedslot();
    void readReadSlot();
};

#endif // DIALOG_H

 服务器源文件

#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    // 设置窗口标记,始终前台显示
    setWindowFlags(Qt::WindowStaysOnTopHint);
    server = new QTcpServer(this);
    bool result = server->listen(QHostAddress::Any,8887);
    if(result)
    {
        showMessage("监听服务器开启成功,端口号8887");
        connect(server,SIGNAL(newConnection()),this,SLOT(newConnectionSlot()));
    }else
    {
        QMessageBox::critical(this,"错误","监听服务开启失败!");
    }
}

Dialog::~Dialog()
{
    if(server->isListening()) // 如果在监听
        // 关闭服务器
        server->close();
    delete ui;
}
void Dialog::showMessage(QString msg)
{
    // 先拿到当前时间和日期
    QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    ui->textBrowser->append(time);
    ui->textBrowser->append(msg);
    ui->textBrowser->append("");
}

void Dialog::newConnectionSlot()
{
    if(socket!=NULL&&socket->isOpen())
    {
        socket->close();
    }
    showMessage("新连接来了!");
    socket = server->nextPendingConnection();
    connect(socket,SIGNAL(disconnected()),this,SLOT(disconnectedslot()));
    QString ip = socket->peerAddress().toString();
    int port = socket->peerPort();
    QString text = "IP地址:";
    text = text+ip.append(":").append(QString::number(port));
    showMessage(text);

}
void Dialog::disconnectedslot()
{
    QString ip = socket->peerAddress().toString();
    int port = socket->peerPort();
    QString text = "IP地址:";
    text = text+ip.append(":").append(QString::number(port));
    text.append("离开了");
    showMessage(text);

}
void Dialog::readReadSlot()
{
    //仍然使用文本流对象读取
        QTextStream input(socket);
        // 读取所有信息
        QString text = input.readAll();
        // 显示
        showMessage(text);
}

 客户端头文件

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
// 网络相关类
#include <QTcpSocket>
#include <QTextStream>
#include <QtWidgets>

namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

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

private:
    Ui::Dialog *ui;
    QTcpSocket *client; // 网络连接对象

private slots:
    void btnConnClickedSlot(); // 连接按钮点击的槽函数
    void connectedSlot(); // 连接成功的槽函数
    void disconnectedSlot(); // 断开连接的槽函数
    void btnSendClickedSlot();

};

#endif // DIALOG_H

客户端源文件

 

#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    // 设置窗口标记,始终前台显示
    setWindowFlags(Qt::WindowStaysOnTopHint);
    client = new QTcpSocket(this);
    connect(ui->pushButtonConn,SIGNAL(clicked()),this,SLOT(btnConnClickedSlot()));
    connect(client,SIGNAL(connected()),this,SLOT(connectedSlot()));
    connect(client,SIGNAL(disconnected()),this,SLOT(disconnectedSlot()));
    connect(ui->pushButtonSend,SIGNAL(clicked()),this,SLOT(btnSendClickedSlot()));
}

Dialog::~Dialog()
{
    delete ui;
    // 如果连接开启,则关闭
    if(client->isOpen())
        client->close();
}

void Dialog::btnConnClickedSlot()
{
    // 获取用户输入(默认输入都是正确的)
    QString ip = ui->lineEditIp->text();
    int port = ui->spinBox->value();
    // 发起连接请求
    client->connectToHost(ip,port);
}

void Dialog::connectedSlot()
{
    // 屏蔽连接按钮
    ui->pushButtonConn->setEnabled(false);
    ui->pushButtonConn->setText("已连接");
    // 开启发送按钮
    ui->pushButtonSend->setEnabled(true);
}

void Dialog::disconnectedSlot()
{
    // 回复连接按钮
    ui->pushButtonConn->setEnabled(true);
    ui->pushButtonConn->setText("连接");
    // 屏蔽发送按钮
    ui->pushButtonSend->setEnabled(false);
    // 弹个窗展示错误信息
    QString text = client->errorString();
    QMessageBox::warning(this,"提示",text.prepend("连接已断开!"));
}
void Dialog::btnSendClickedSlot()
{
    QString user = ui->lineEditUser->text();
    if(user=="")
    {
        QMessageBox::warning(this,"提示","请输入昵称");
        return;
    }
    QString msg=ui->lineEditMsg->text();
    if(msg=="")
    {
        QMessageBox::warning(this,"提示","请输入要发送的信息!");
        return;
    }
    QTextStream output(client);
    output<<user<<QString(":")<<msg;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值