Description▲
The EchoClient example implements a WebSocket client that sends a message to a WebSocket server and dumps the answer that it gets back. This example should ideally be used with the EchoServer example.
Code▲
We start by connecting to the `connected()` signal.
EchoClient::
EchoClient(const
QUrl &
amp;url, bool
debug, QObject *
parent) :
QObject(parent),
m_url(url),
m_debug(debug)
{
if
(m_debug)
qDebug() &
lt;&
lt; "WebSocket server:"
&
lt;&
lt; url;
connect(&
amp;m_webSocket, &
amp;QWebSocket::
connected, this
, &
amp;EchoClient::
onConnected);
connect(&
amp;m_webSocket, &
amp;QWebSocket::
disconnected, this
, &
amp;EchoClient::
closed);
m_webSocket.open(QUrl(url));
}
After the connection, we open the socket to the given url.
void
EchoClient::
onConnected()
{
if
(m_debug)
qDebug() &
lt;&
lt; "WebSocket connected"
;
connect(&
amp;m_webSocket, &
amp;QWebSocket::
textMessageReceived,
this
, &
amp;EchoClient::
onTextMessageReceived);
m_webSocket.sendTextMessage(QStringLiteral("Hello, world!"
));
}
When the client is connected successfully, we connect to the `onTextMessageReceived()` signal, and send out "Hello, world!". If connected with the EchoServer, we will receive the same message back.
void
EchoClient::
onTextMessageReceived(QString message)
{
if
(m_debug)
qDebug() &
lt;&
lt; "Message received:"
&
lt;&
lt; message;
m_webSocket.close();
}
Whenever a message is received, we write it out.