我看过VoidRealm的Youtube视频C++ Qt 67 - QTCPServer - a basic TCP server application,并遵照他的指示,但是我无法连接到我用Telnet创建的QTcpServer。
我的守则:
//myserver.h
#ifndef MYSERVER_H
#define MYSERVER_H
#include <QObject>
#include <QDebug>
#include <QTcpServer>
#include <QTcpSocket>
class MyServer : public QObject
{
Q_OBJECT
public:
explicit MyServer(QObject *parent = nullptr);
void newConnection();
signals:
private:
QTcpServer *server;
};
#endif // MYSERVER_H//myserver.cpp
#include "myserver.h"
MyServer::MyServer(QObject *parent)
: QObject{parent}
{
server = new QTcpServer(this);
connect(server,SIGNAL(newConnection()),this,SLOT(newConnection()));
if(!server->listen(QHostAddress::Any, 1234))
{
qDebug() << "Server could not start!";
}else{
qDebug() << "Server started!";
}
}
void MyServer::newConnection()
{
QTcpSocket *socket = server->nextPendingConnection();
socket->write("hello client\r\n");
socket->flush();
socket->waitForBytesWritten(3000);
socket->close();
}在控制台屏幕上运行以下代码
qt.core.qobject.connect: QObject::connect: No such slot MyServer::newConnection() in ..\First_Server\myserver.cpp:8
Server started!但是,当我打开命令提示符并执行以下步骤时:
...>telnetWelcome to Microsoft Telnet Client
Escape Character is 'CTRL+]'
Microsoft Telnet> open 127.0.0.1 1234
Connecting To 127.0.0.1...这不是连接。有人能告诉我我做错了什么吗?我正在使用QT6.3.0。
发布于 2022-07-29 07:50:52
您的错误消息指示问题:
qt.core.qobject.connect: QObject::connect:没有这样的插槽MyServer::newConnection()在..\First_Server\myserver.cpp:8服务器启动!
您已经在这里创建了信号和插槽之间的连接。
connect(server,SIGNAL(newConnection()),this,SLOT(newConnection()));首先,当信号变得混乱时,使用与信号相同的插槽名并不是一个好主意。例如,我会把你的插槽称为"handleNewConnection“。其次,您应该使用“新”信号槽语法。第三,也是最重要的是,您还没有将newConnection()方法声明为一个槽。您需要在头文件中声明它:
private Q_SLOTS:
void newConnection();如果必须从外部访问插槽,您也可以公开这些插槽,看起来您只能在这里私下使用它。
https://stackoverflow.com/questions/73162859
复制相似问题