Chapter 5

Connecting to PlayOK

We now have the two pieces we need on the client side: the configuration module knows how to describe the PlayOK connection, and the engine module knows how to communicate with our chess engine. The next step is to create the PlayOK client itself and establish the WebSocket connection.

This chapter focuses only on the connection layer. We are not going to implement PlayOK functionality yet. Those features will be added later as we reverse engineer the corresponding messages.

The PlayOK Client

Our PlayOK client is represented by the PlayOK class.

class PlayOK:
    def __init__(self):
        # WebSocket state
        self.ws = None
        self.keep_alive_thread = None
        self.receive_thread = None
        self.running = False
        
        # PlayOK state
        self.table_range = (0, 0)
        self.active_table = 0
        self.active_game = NONE
        self.user_name = ""
        self.player_white = ""
        self.player_black = ""
        self.engine_side = NONE
        self.first_move = NONE
        
        # Chess engine
        self.engine = ChessEngine()

The class contains three groups of state: WebSocket state, PlayOK game state, and chess engine state.

At this stage, most of the PlayOK game variables are simply initialized. We will use them later when we start processing the messages sent by the server.

WebSocket State

The first group describes the connection itself.

self.ws = None
self.keep_alive_thread = None
self.receive_thread = None
self.running = False

self.ws will hold the actual WebSocket object. Before connecting, it is None.

keep_alive_thread and receive_thread will later contain the background threads responsible for keeping the connection alive and receiving messages from PlayOK.

Finally, running is our main connection state. It tells the background threads whether the client should continue operating.

Using a single state variable like this is useful because both background loops need to stop when the connection is closed. Instead of maintaining separate shutdown conditions, they can simply check whether self.running is still true.

PlayOK State

The next group contains information about the user's current PlayOK session.

self.table_range = (0, 0)
self.active_table = 0
self.active_game = NONE
self.user_name = ""
self.player_white = ""
self.player_black = ""
self.engine_side = NONE
self.first_move = NONE

These variables do not establish the WebSocket connection itself. They represent information that we will learn from the PlayOK server after the connection has been established.

For example, active_table will eventually identify the table on which our bot is currently playing. active_game will track the current game, while player_white and player_black will contain the players taking part in it.

engine_side will tell us whether our engine is playing White or Black. Until the server tells us which side we have taken, its value is NONE.

At this stage, we do not need to do anything with these variables. We are simply preparing the state that the later parts of the client will use.

Creating the Chess Engine

The final line of the constructor creates our chess engine object:

self.engine = ChessEngine()

This means that the PlayOK client owns an instance of the engine module. When a game eventually starts, the PlayOK client will be able to pass opponent moves to the engine and request a response.

Notice that the PlayOK class does not implement any chess logic itself. It delegates that responsibility to ChessEngine. This keeps the two parts independent.

Resetting PlayOK State

The client also has a method for resetting the state associated with a game.

def reset_state(self):
self.active_table = 0
self.active_game = NONE
self.player_white = ""
self.player_black = ""
self.engine_side = NONE
self.first_move = NONE

This is useful because the same client can participate in more than one game during its lifetime. When a game finishes, we need a reliable way to remove information from the previous game before starting another one.

Again, this method does not close the WebSocket connection. It only resets the PlayOK game state.

Establishing the WebSocket Connection

The actual connection is created by the connect() method.

def connect(self):
    try:
        self.ws = websocket.WebSocket()
        self.ws.connect(WS_URL, origin="null", header=["User-Agent: " + USER_AGENT])
        self.running = True
        self.send_message(CREDENTIALS)
        self.keep_alive_thread = threading.Thread(target=self.keep_alive, daemon=True)
        self.receive_thread = threading.Thread(target=self.receive_messages, daemon=True)
        self.keep_alive_thread.start()
        self.receive_thread.start()
    except Exception as e:
        print("SYSTEM: WebSocket connection error:", e)
        self.running = False

The first line creates a WebSocket object provided by the websocket Python package.

self.ws = websocket.WebSocket()

At this point we have a WebSocket object, but it is not connected to PlayOK yet.

The actual connection happens here:

self.ws.connect(
    WS_URL,
    origin="null",
    header=["User-Agent: " + USER_AGENT]
)

WS_URL comes from config.py and contains the PlayOK WebSocket endpoint. We also provide the browser-like user-agent that we observed while inspecting the original PlayOK client.

The Origin value is also explicitly provided. This is important because a WebSocket handshake contains HTTP headers, and servers can use those headers when deciding whether to accept a connection. Our goal here is to reproduce the relevant connection behavior of the browser client rather than simply opening an arbitrary WebSocket connection.

The Connection Handshake

Although the code above looks like a single function call, a WebSocket connection begins with an HTTP-based handshake.

The client first contacts the server and asks to upgrade the HTTP connection to WebSocket. If the server accepts the request, the connection is upgraded and becomes a persistent WebSocket connection.

After that upgrade, we no longer communicate with PlayOK by making independent HTTP requests for every message. Instead, the same connection remains open and both sides can send messages through it.

This is the fundamental reason WebSockets are useful for an application such as an online chess server. The server can immediately notify the browser about changes without requiring the browser to repeatedly ask whether something happened.

Marking the Client as Running

Once the connection succeeds, we set:

self.running = True

This is deliberately done only after the WebSocket connection has been established. The background threads use this value to determine whether they should continue running.

If the connection fails, execution jumps to the exception handler and running remains false.

Sending the Initial Credentials Message

After connecting, the first application-level message we send is the credential or initialization message:

self.send_message(CREDENTIALS)

This is separate from the WebSocket handshake. The handshake establishes the WebSocket transport, while this message belongs to the PlayOK application protocol running on top of that transport.

This distinction is important throughout the project. There are really two layers involved:

  1. The WebSocket layer establishes and maintains the communication channel.
  2. The PlayOK protocol defines what the messages inside that channel mean.

Our reverse engineering work is primarily concerned with the second layer.

Why Use Background Threads?

After sending the initial message, the client starts two background threads.

self.keep_alive_thread = threading.Thread(
    target=self.keep_alive,
    daemon=True
)

self.receive_thread = threading.Thread(
    target=self.receive_messages,
    daemon=True
)

The first thread handles the periodic keep-alive activity. The second thread will continuously receive messages from the WebSocket.

This separation is necessary because receiving from a WebSocket is normally a blocking operation. If the main program waited for incoming messages continuously, it would not be able to perform other tasks at the same time.

Similarly, keep-alive messages need to be sent periodically even when the server is not sending anything to us.

Using separate threads allows both activities to happen independently:

Main program
    │
    ├── Keep-alive thread
    │       └── periodically sends messages
    │
    └── Receive thread
            └── waits for incoming messages

Both threads are marked as daemon threads. This means they will not prevent the Python process from exiting when the main program terminates.

Starting the Threads

After creating the threads, we start them:

self.keep_alive_thread.start()
self.receive_thread.start()

At this point the basic client is alive. The WebSocket connection is established, the initial PlayOK message has been sent, one thread is responsible for keeping the session alive, and another is waiting for messages from the server.

The receive method is not implemented in this chapter because it will become the subject of the next chapter. For now, the important part is understanding where it fits into the architecture.

Keeping the Connection Alive

The keep-alive logic is implemented in the keep_alive() method.

def keep_alive(self):
    while self.running:
        # Tell server user is online
        time.sleep(DELAY)
        if not self.running: break
        self.send_message(KEEP_ALIVE)
        
        # Track state variables
        self.user_status()

The loop continues while self.running is true.

First, the client waits for the configured delay:

time.sleep(DELAY)

After the delay, it checks the connection state again. This second check is useful because the client may have been closed while the thread was sleeping.

If the client is still running, it sends the keep-alive message defined in config.py:

self.send_message(KEEP_ALIVE)

Our configuration defines this message as:

{"i": []}

This is an example of an application-level heartbeat. It is not the same thing as a low-level WebSocket ping frame. It is an ordinary PlayOK message whose meaning is defined by the PlayOK protocol.

After sending the keep-alive, the client also requests the current user information:

self.user_status()

It also sends a user information request specifically to force PlayOK to report the table associated with the current user. We use this response to detect state changes such as being booted from a table. Without periodically requesting this information, the bot can continue believing that it is still sitting at a table after another user has removed it, causing its internal state to become desynchronized from the actual PlayOK state.

Later, the receive-message logic will use this information to detect such changes and update the current table and game state variables accordingly.

Checking User Status

The user_status() method is intentionally very small:

def user_status(self):
    self.send_message({"i": [USER_INFO], "s": [self.user_name]})

It constructs a PlayOK protocol message using the USER_INFO opcode from config.py.

The important design principle here is that the rest of the application does not need to know that USER_INFO corresponds to a particular numeric value. The protocol constant gives the message a meaningful name.

Sending Messages

All outgoing PlayOK messages go through a single method:

def send_message(self, message):
    if not self.ws or not self.running:
        print("SYSTEM: WebSocket is not connected")
        return
    if isinstance(message, dict):
        message = json.dumps(message, separators=(",", ":"))
        try: self.ws.send(message)
        except Exception as e:
            print("SYSTEM:", e)
            self.running = False

This gives the client one central place for sending application-level messages.

Before sending anything, the method checks whether a WebSocket exists and whether the client is currently running:

if not self.ws or not self.running:
    print("SYSTEM: WebSocket is not connected")
    return

This prevents other parts of the application from attempting to send messages after the connection has already been closed or before it has been established.

Converting Python Data to JSON

Most of our protocol messages are represented inside Python as dictionaries and lists. The WebSocket, however, needs the actual serialized message.

Therefore, if the supplied value is a Python dictionary, we convert it to JSON:

message = json.dumps(message, separators=(",", ":"))

The custom separators remove unnecessary spaces from the generated JSON. This produces a compact representation that is closer to the compact messages observed in the browser's WebSocket traffic.

For example, a Python dictionary representing a protocol message can be converted into a compact JSON string before being sent through the WebSocket.

There is an important detail here that we will encounter again later: serializing a Python object into JSON is not the same thing as understanding the PlayOK protocol. JSON only describes the outer representation. The meaning of the arrays, numbers, and strings inside that JSON is defined by PlayOK itself.

Handling Send Errors

The actual WebSocket transmission is wrapped in an exception handler:

try: self.ws.send(message)
except Exception as e:
    print("SYSTEM:", e)
    self.running = False

If the connection disappears or the socket encounters another error while sending, the client reports the error and marks itself as no longer running.

Changing running to false also gives the background threads a signal to stop. The keep-alive loop will eventually see that the client is no longer running and terminate.

Closing the Connection

The opposite operation is handled by close().

def close(self):
    self.running = False
    if self.ws:
        try:
            self.ws.close()
            self.engine.close()
            print("SYSTEM: WebSocket connection closed")
            print("SYSTEM: Chess engine closed")
        except Exception: pass

The first thing we do is set running to false. This tells the background threads that the application is shutting down.

We then close the WebSocket itself. Finally, we close the chess engine that was created when the PlayOK object was initialized.

It is important that both resources are closed. The WebSocket is an external network connection, while the UCI engine is an external process. Leaving either one running after the bot exits can create problems during development and testing.

What We Have Built So Far

At the end of this chapter, our client still cannot play chess. It cannot accept a challenge, join a table, detect a game, or send a move. That is intentional.

What we have built is the foundation underneath all of those features:

  1. Create the PlayOK client.
  2. Start the UCI chess engine.
  3. Open the PlayOK WebSocket connection.
  4. Send the initial PlayOK connection message.
  5. Start a background keep-alive loop.
  6. Start a background receive loop.
  7. Provide a central method for sending JSON messages.
  8. Provide a clean way to close the connection and engine.

The most important thing to understand is that we now have a persistent communication channel. The browser normally maintains this channel while the user is on PlayOK, and our Python client will do the same thing.

From here onward, the interesting part begins. Instead of simply connecting to PlayOK, we need to understand what PlayOK sends back to us and what those messages mean. The receive thread will become our window into the server's state, and by examining those messages we can gradually teach our simplified client how to behave like the original browser client.

Transport Is Not the Protocol

The WebSocket gives us a persistent connection, but it does not tell us what the messages mean. The actual PlayOK protocol lives on top of that connection. First we establish the transport; then we implement the application-level messages that travel through it.