OBE_Socket class

class optbayesexpt.obe_socket.Socket(role, ip_address='', port=61981)[source]

Bases: object

Handles TCP communications

The Socket can be configured either as a ‘server’ or a ‘client’. Server sockets wait for connections, receive messages and send replies. Client sockets initiate connections and receive replies.

The message protocol uses messages formatted as JSON strings, each prependend by the string length as a zero-padded, 10-digit decimal number. The general form is

dddddddddd<JSON-formatted string>

Command messages from the client use a JSON object:

dddddddddd{“command”: <command_str>[, <label_str>: <value_str>[, …]].

Example messages
  • 0000000038{"command": "goodset", "pickiness": 4}

  • 0000000019{"command": "done"}

  • 0000000004"OK"

  • role (str) – either ‘client’ to configure the Socket to initiate communications or ‘server’ to listen and respond.

  • ip_address (str) – Identifies the computer host to communicate with. The default of ‘’ is the localhost, enabling communications between processes on the host computer.

  • port (int) – the TCP port used for communications. The default value 61981 was chosen chosen randomly in the unassigned port range 49152 to 65535.


for the ‘server’ role, a socket.socket object configured to listen and accept connections


for the ‘client’ role, a socket.socket object configured to initiate connections and send messages


Close the communication connection.

Only clients need to close connections once they’re done communicating. No need to call this for servers.


Wait for and process messages on the TCP port

Blocks until a connection is made, then reads the number of bytes specified in the first 10 characters. Reads the connection until the full message is received, then decodes the messages string.


The message string decoded and repackaged as a python object


Formats and sends a message

This method formats the contents argument into the message format, opens a connection and sends the contents as a message.


contents – Any JSON format-able object. Briefly, python’s str, int, float, list, tuple, and dict objects.


json.dumps() is not able to format numpy arrays. To send numpy arrays, the numpy.tolist() method is a convenient way to list-ify a numpy array. For example:


Sends a command and receives a response.

Run from a client socket, this method sends a command message and receives a response. The connection is then closed.

  • command – a JSON-ifiable python object to be interpreted by the

  • recipient.


a pyhton object decoded from the reply message