大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺
#include "mainwindow.h"
#include "ui_clientWindow.h"
#include <QMessageBox>
#include <QDateTime>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::clientWindow)
{
ui->setupUi(this);
init();
initConnect();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::slotReadError(QAbstractSocket::SocketError error)
{
mTcpClient->disconnectFromHost();
ui->mConnectButton->setText(QStringLiteral("连接"));
mSwitch = false;
QMessageBox msgBox;
msgBox.setText(tr("failed to connect server because %1").arg(mTcpClient->errorString()));
msgBox.exec();
}
void MainWindow::slotReadData()
{
QByteArray buffer = mTcpClient->readAll();
if(!buffer.isEmpty())
{
ui->mReceiveEdit->append(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
ui->mReceiveEdit->append(QString::fromUtf8(buffer));
}
}
void MainWindow::slotConnectNetwork()
{
if(mSwitch)
{
//断开
mTcpClient->disconnectFromHost();
if (mTcpClient->state() == QAbstractSocket::UnconnectedState || mTcpClient->waitForDisconnected(1000)) //已断开连接则进入if{}
{
ui->mConnectButton->setText(QStringLiteral("连接"));
ui->mSendButton->setEnabled(false);
}
mSwitch = false;
}
else
{
//连接
mTcpClient->connectToHost(ui->mAddrEdit->text(), static_cast<quint16>(ui->mPortEdit->text().toInt()));
if(mTcpClient->waitForConnected(1000)) // 连接成功则进入if{}
{
ui->mConnectButton->setText(QStringLiteral("断开"));
ui->mSendButton->setEnabled(true);
}
mSwitch = true;
}
}
void MainWindow::slotSendText()
{
QString data = ui->mSendTextEdit->toPlainText();
if(data.simplified().size())
{
mTcpClient->write(data.toUtf8());
}
ui->mSendTextEdit->clear();
}
void MainWindow::init()
{
setWindowTitle(QStringLiteral("Client"));
mTcpClient = new QTcpSocket(this); //实例化tcpClient
mTcpClient->abort(); //取消原有连接
ui->mSendButton->setEnabled(false);
}
void MainWindow::initConnect()
{
connect(mTcpClient, &QTcpSocket::readyRead, this,&MainWindow::slotReadData);
connect(mTcpClient, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(slotReadError(QAbstractSocket::SocketError)));
connect(ui->mConnectButton,&QPushButton::clicked,this,&MainWindow::slotConnectNetwork);
connect(ui->mClearButton,&QPushButton::clicked,this,[this](){
ui->mReceiveEdit->clear();});
connect(ui->mSendButton,&QPushButton::clicked,this,&MainWindow::slotSendText);
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/195503.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...