//MainWindow.h文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMessageBox>
//TCP
#include <QTcpServer>
#include <QTcpSocket>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
void InitialGUI();
QTcpServer* server;
QTcpSocket* socket;
QString server_ip;
QString server_port;
private:
Ui::MainWindow *ui;
private slots:
void ConnectServer();
void DisconnectServer();
void SendData();
void ReceiveData();
void Server_New_Connect();
};
#endif // MAINWINDOW_H
//MainWindow.cpp文件
#include "MainWindow.h"
#include "ui_MainWindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
InitialGUI();
// InitialServer();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::InitialGUI()
{
connect(ui->btnConnect,SIGNAL(clicked()),this,SLOT(ConnectServer()));
connect(ui->btnDisconnect,SIGNAL(clicked()),this,SLOT(DisconnectServer()));
connect(ui->btnSend,SIGNAL(clicked()),this,SLOT(SendData()));
//初始化Server
server = new QTcpServer();
//服务器被客户端访问时,会触发newconnection信号,把服务端和客户端关联起来
connect(server,SIGNAL(newConnection()),this,SLOT(Server_New_Connect()));
ui->txtEdit_IP->setText("160.160.0.1");
ui->txtEdit_Port->setText("2001");
}
void MainWindow::ConnectServer()
{
//定义IP和Port
server_ip = ui->txtEdit_IP->toPlainText();
server_port = ui->txtEdit_Port->toPlainText();
//开启监听
if(server->listen(QHostAddress(server_ip),server_port.toInt()))
{
//监听成功
}
else
{
//监听失败
QMessageBox::warning(this,"warning",tr("Listen Failed!"),QMessageBox::Yes,QMessageBox::No);
}
}
void MainWindow::Server_New_Connect()
{
//获取客户端连接
this->socket = this->server->nextPendingConnection();
//服务器收到客户端数据时,相应readyRead信号
connect(this->socket,SIGNAL(readyRead()),this,SLOT(ReceiveData()));
//服务器收到客户端断开连接时,触发disconnected信号
// connect(this->socket,SIGNAL(disconnected()),this,SLOT(DisconnectServer()));
}
void MainWindow::DisconnectServer()
{
this->socket->close();
this->server->close();
}
void MainWindow::ReceiveData()
{
QByteArray arr = this->socket->readAll();
QString msg(arr);
this->ui->txtEdit_MsgReceive->append(msg);
}
void MainWindow::SendData()
{
QString str = this->ui->txtEdit_MsgSend->toPlainText();
QByteArray arr = str.toLocal8Bit();
qint64 r_1 = this->socket->write(arr);
bool r_2 = this->socket->flush();
if(r_1!= -1 && r_2 == 1)
{
if(r_1 == 0)
{
QMessageBox::warning(this,"warning",tr("Write Data Failed!"),QMessageBox::Yes,QMessageBox::No);
}
// QMessageBox::warning(this,"warning",tr("Write Data Successful!"),QMessageBox::Yes,QMessageBox::No);
}
}