Warning

This section contains snippets that were automatically translated from C++ to Python and may contain errors.

QWebSocket client example

A sample WebSocket client that sends a message and displays the message that it receives back.

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.

def __init__(self, url, debug, parent):
    QObject(parent),
    m_debug(debug)

    if m_debug:
        print("WebSocket server:", url)
    m_webSocket.connected.connect(self.onConnected)
    m_webSocket.disconnected.connect(self.closed)
    m_webSocket.open(url)

After the connection, we open the socket to the given url.

def onConnected(self):

    if m_debug:
        print("WebSocket connected")
    m_webSocket.textMessageReceived.connect(
            self.onTextMessageReceived)
    m_webSocket.sendTextMessage("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.

def onTextMessageReceived(self, message):

    if m_debug:
        print("Message received:", message)
    m_webSocket.close()

Whenever a message is received, we write it out.