做了一个简单的客户端与服务端的demo
服务端:
// .h
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_btnsend_clicked();
void on_btncloss_clicked();
private:
Ui::MainWindow *ui;
QTcpServer *tcpserver;
QTcpSocket *tcpsocket;
};
//.cpp
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
tcpserver = new QTcpServer(this);
tcpserver->listen(QHostAddress::Any,8888);
/* tcpsocket = new QTcpSocket(this);//服务器不用newQTcpSocket 当tcpServer被tcpClient访问时,会发出newConnection()信号,因此为该信号添加信号槽,并用一个 QTcpSocket对象接受客户端访问
*/
//这里槽函数一定要嵌套槽函数 不然无法连接
connect(tcpserver,&QTcpServer::newConnection,this,[=](){
tcpsocket = tcpserver->nextPendingConnection();//建立socket
QString ip = tcpsocket->peerAddress().toString(); //获取连接的 ip地址
quint64 port = tcpsocket->peerPort(); //获取连接的 端口号
QString temp = QString("[%1:%2]链接成功").arg(ip).arg(port); //显示连接成功
ui->read->append(temp);
connect(tcpsocket,&QTcpSocket::readyRead,this,[=](){
QString str = tcpsocket->readAll();
ui->read->append("客户端:"+str);
});
connect(tcpsocket,&QTcpSocket::disconnected,this,[=](){
//tcpsocket->disconnectFromHost();这会发出disconnected信号 参考帮助文档
qDebug()<<tcpsocket;
tcpsocket->deleteLater();
qDebug()<<tcpsocket;
qDebug()<<"客户端退出";
});
});
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_btnsend_clicked()
{
QString str = ui->write->toPlainText();
tcpsocket->write(str.toUtf8().data());
ui->read->append("服务端:"+str);
}
void MainWindow::on_btncloss_clicked()
{
qDebug()<<"服务器退出";
}
客户端简单很多:
// .h
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_connectServer_clicked();
void on_btnsend_clicked();
void on_btncloss_clicked();
private:
Ui::MainWindow *ui;
QTcpSocket *socket;
};
//.cpp
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
socket = new QTcpSocket(this);
connect(socket,&QTcpSocket::connected,this,[=](){
ui->read->setText("服务器连接成功...");
});
connect(socket,&QTcpSocket::readyRead,this,[=](){
QString str = socket->readAll();
ui->read->append("服务器:"+str);
});
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_connectServer_clicked()
{
//获取IP 端口号
QString ip = ui->edtip->text();
//unsigned short port1 = ui->edtport->text().toUShort(); //方法一
quint16 port = ui->edtport->text().toInt();//方法二
//与服务器连接
socket->connectToHost(ip,port);
}
void MainWindow::on_btnsend_clicked()
{
QString str = ui->write->toPlainText();
socket->write(str.toUtf8().data());
ui->read->append("客户端:"+str);
}
void MainWindow::on_btncloss_clicked()
{
//首先调用 disconnectFromHost() 来尝试优雅地断开连接,然后在需要时调用 close() 来确保套接字被关闭。但是,具体的使用情况可能因应用程序的需求和网络环境的不同而有所不同
socket->disconnectFromHost();
socket->close();
}
运行效果: