服务器后台使用 Linux + epoll + tcp 构建的
请问客户端使用 Qt + QTcpSocket 创建
自测客户端无法连接到服务端
疑问:
这种方式有可行吗?
服务器后台使用 Linux + epoll + tcp 构建的
请问客户端使用 Qt + QTcpSocket 创建
自测客户端无法连接到服务端
疑问:
这种方式有可行吗?
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QAbstractSocket>
#include <QString>
#include <QDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
QTcpServer *tcpServer;
//槽函数来接收客户端的连接请求;
private slots:
void mNewConnection();
void receiveMessage();
void mStateChanged(QAbstractSocket::SocketState);
void on_pushButton_3_clicked();
void on_pushButton_clicked();
void on_pushButton_2_clicked();
};
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
this->setWindowTitle("服务端");
//设置初始不可用
ui->pushButton_2->setEnabled(false);
tcpServer = new QTcpServer(this);
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(mNewConnection()));
}
Widget::~Widget()
{
delete ui;
}
void Widget::mNewConnection()
{
//与客户端连接;
QTcpSocket *temTcpSocket = tcpServer->nextPendingConnection();
//打印ip地址;
QString ipAddr = temTcpSocket->peerAddress().toString();
ui->textBrowser->append("客户端IP地址:"+ipAddr);
//打印port地址;
quint16 port = temTcpSocket->peerPort();
ui->textBrowser->append("客户端port地址:"+QString::number(port));
connect(temTcpSocket,SIGNAL(readyRead()),this,SLOT(receiveMessage()));
//
connect(temTcpSocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),
this,SLOT(mStateChanged(QAbstractSocket::SocketState)));
}
//接收消息
void Widget::receiveMessage()
{
//接收消息并打印;
QTcpSocket *temTcpSocket = (QTcpSocket*)sender();
ui->textBrowser->append("客户端:"+temTcpSocket->readAll());
}
void Widget::mStateChanged(QAbstractSocket::SocketState state)
{
QTcpSocket *temTcpSocket = (QTcpSocket *)sender();
switch (state) {
case QAbstractSocket:: UnconnectedState:
ui->textBrowser->append("客户端断开");
//断开释放内存;
temTcpSocket->deleteLater();
break;
//经调试,这句话不会打印;
case QAbstractSocket:: ConnectedState:
ui->textBrowser->append("客户端已连接");
break;
default:
break;
}
}
//发送信息;
void Widget::on_pushButton_3_clicked()
{
//通过容器向所有的客户端发送信息;
QList <QTcpSocket*> socketList = tcpServer->findChildren<QTcpSocket*>();
qDebug()<<"客户端的数量:"<<socketList.count()<<endl;
if(socketList.count() == 0)
{
ui->textBrowser->append("没有客户端连接!");
return;
}
foreach(QTcpSocket *temSocket,socketList)
{
temSocket->write(ui->lineEdit->text().toUtf8());
}
ui->textBrowser->append("服务端:"+ui->lineEdit->text().toUtf8());
}
//连接客户端;
void Widget::on_pushButton_clicked()
{
tcpServer->listen(QHostAddress("192.168.128.22"),9999);
ui->textBrowser->append("开始监听...");
ui->pushButton_2->setEnabled(true);
ui->pushButton->setEnabled(false);
}
//停止监听
void Widget::on_pushButton_2_clicked()
{
tcpServer->close();
ui->pushButton_2->setEnabled(false);
ui->pushButton->setEnabled(true);
}