I tried to modify the code from the qt documentation, to process strings entered from the keyboard, and if it is not a command (starting with '-'), then send it to the server:
echoclient.cpp :
//! [constructor]
EchoClient::EchoClient(const QUrl &url, bool debug, QObject *parent) :
QObject(parent),
m_debug(debug)
{
if (m_debug)
qDebug() << "WebSocket server:" << url;
connect(&m_webSocket, &QWebSocket::connected, this, &EchoClient::onConnected);
connect(&m_webSocket, &QWebSocket::disconnected, this, &EchoClient::closed);
m_webSocket.open(url);
}
//! [constructor]
//! [onConnected]
void EchoClient::onConnected()
{
if (m_debug)
qDebug() << "WebSocket connected";
m_webSocket.sendTextMessage(QStringLiteral("Hello, world!"));
connect(&m_webSocket, &QWebSocket::textMessageReceived,
this, &EchoClient::onTextMessageReceived);
}
//! [onConnected]
//! [onTextMessageReceived]
void EchoClient::onTextMessageReceived(QString message)
{
if (m_debug)
qDebug() << "Message received:" << message;
//m_webSocket.close();
}
//! [onTextMessageReceived]
void EchoClient::Run() {
CommandProcessing();
}
void EchoClient::CommandProcessing() {
QTextStream qtin(stdin);
while(true) {
QString text;
text = qtin.readLine();
if (text[0] == '-') {
// if text is command
}
else {
// Send msg
m_webSocket.sendTextMessage(text);
}
}
}
main.cpp
int main(int argc, char *argv[])
{
using namespace Qt::Literals::StringLiterals;
QCoreApplication a(argc, argv);
QUrl url("ws://localhost:1234");
qDebug() << url;
EchoClient client(url, true);
QObject::connect(&client, &EchoClient::closed, &a, &QCoreApplication::quit);
client.Run();
return a.exec();
}
I want to process strings after establishing a connection between the client and the server, but when using the Run()
method, the client cannot even connect to the server; without Run()
everything works. I also tried to use the isValid()
method of m_webSocket
to see if I could work with it, but it also did not give results. I commented out m_webSocket.close()
to continue working with websockets