我正在使用 Qt 示例中的 Web 客户端和 Web 服务器
echoclient.cpp - https://pastebin.com/z8bgfQzE 客户端 main.cpp - https://pastebin.com/g1DtjjYa
echoserver.cpp - https://pastebin.com/V7aqHu2L 服务器 main.cpp - https://pastebin.com/Ni7CAXKu
我有一个简单的
Send
老虎机:
void EchoClient::Send() {
QTextStream qtin(stdin);
QString word;
qtin >> word;
int sBytes = m_webSocket.sendTextMessage(word);
std::cout << "Send bytes: " << sBytes << std::endl;
}
我一直想输入数据,但我不知道我可以绑定什么作为信号来触发槽:
connect(???, ???, this, &EchoClient::Send);
我尝试覆盖 Enter 按键,但我无法在 Qt 控制台应用程序中执行此操作。
如果您希望在每次读取单词之间处理主循环中的事件,则需要使用连接。只需 1 个类即可实现此目的,但我建议您限制
EchoClient
的职责,使其仅进行通信。将从输入流中读取其他内容。
更正
Send
,使其仅发送收到的单词:
void EchoClient::Send(const QString& word) {
int sBytes = m_webSocket.sendTextMessage(word);
std::cerr << "Send bytes: " << sBytes << std::endl;
}
另一个类负责从输入流中读取。我们希望它读取一个 1,让主循环处理事件,然后准备读取下一个单词,依此类推。
其结果非常粗略:
class KeyboardReader : public QObject {
Q_OBJECT
public:
KeyboardReader() {
//Connection to make KeyboardReader::readWord loop upon itself by the event loop
QObject::connect(this, &KeyboardReader::start, this, &KeyboardReader::readWord,
Qt::QueuedConnection | Qt::SingleShotConnection);
}
signals:
void start();
void wordReceived(const QString& word);
public slots:
void readWord();
};
void KeyboardReader::readWord() {
QTextStream qtin(stdin);
QString word;
qtin >> word;
emit wordReceived(word);
}
然后,
main
函数应类似于:
int main() {
QCoreApplication a;
EchoClient client;
//Initialize/connect client here
KeyboardReader reader;
//Connection to make the message read by reader propagate to client
QObject::connect(&reader, &KeyboardReader::wordReceived, &client, &EchoClient::Send);
//Connection to make KeyboardReader::readWord loop upon itself in the Qt main loop
QObject::connect(&reader, &KeyboardReader::wordReceived, &reader, &KeyboardReader::readWord);
emit reader.start();
return a.exec();
}