#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QTcpSocket>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowTitle(u8"服务器"); //设置Title
setWindowIcon(QIcon(":/titleIcon.png")); //设置Title图标
ui->portEdit->setText("10554");
//创建监听的服务器对象,相当于serv_sock
tcpsock = new QTcpServer(this);
connect(tcpsock,&QTcpServer::newConnection,this,[=](){ //newConnection()相当于listen()
ui->connectBtn->setDisabled(true);
cln_sock = tcpsock->nextPendingConnection(); //nextPendingConnection()相当于accept()
ui->connectBtn->setDisabled(true);
ui->historyEdit->setText("连接成功!");
msgBox->close();
connect(cln_sock,&QTcpSocket::readyRead,this,[=](){ //cln_sock发送readyRead信号说明信息到了cln_sock,可以读了
QByteArray read_data = cln_sock->readAll(); //利用readAll()都所有数据
ui->historyEdit->append("客户端: "+read_data);
});
staLable->setPixmap(QPixmap(":/right.png").scaled(20,20));
connect(cln_sock,&QTcpSocket::disconnected,this,[=](){
cln_sock->close(); //如果cln_sock收到disconnected消息,就关闭套接字
cln_sock->deleteLater(); //delete cln_sock
staLable->setPixmap(QPixmap(":/error.png").scaled(20,20));
ui->connectBtn->setEnabled(true);
ui->historyEdit->append("断开连接!");
});
});
//设置状态栏
staLable = new QLabel(this);
staLable->setPixmap(QPixmap(":/error.png").scaled(20,20)); //setPixmap()添加图片,scaled()用于设置缩放大小
ui->statusbar->addWidget(new QLabel("连接状态:"));
ui->statusbar->addWidget(staLable);
}
MainWindow::~MainWindow()
{
delete ui;
}
//绑定IP、端口
void MainWindow::on_connectBtn_clicked()
{
unsigned short port = ui->portEdit->text().toUShort(); //text()获取内容为字符串,因为端口类型要是unsigned short,所以在调用toUshort()
tcpsock->listen(QHostAddress::Any,port); //相当于bind()
msgBox = new QMessageBox(QMessageBox::Warning, "警告", "正在寻找连接...", QMessageBox::NoButton, this);
//msgBox->warning(this,"警告","正在寻找连接...");
msgBox->show();
}
//将Edit内容发送到套接字,并在对话框中显示
void MainWindow::on_subBtn_clicked()
{
if(cln_sock->state() == QAbstractSocket::ConnectedState){
QString write_data = ui->subEdit->toPlainText(); //toPlainText()是以纯文本的方式读取Edit内容
cln_sock->write(write_data.toUtf8()); //toUtf8()将内容转换为QByteArray类型
ui->historyEdit->append("服务器: "+write_data);
ui->subEdit->setText(""); //内容发送到historyEdit,
}else{
QMessageBox::warning(this,"警告","请先连接网络");
}
}