TCP/IP#
This protocol carries the messages over a TCP/IP connection.
Note
If a client library is available for your language, you do not need to implement this protocol.
Framing#
Each message is a Message, encoded according to the Protocol Buffers binary format and
prefixed with its size in bytes, encoded as a varint. The following Python functions send and
receive a message:
def encode_varint(value):
"""Encode an int as a protobuf varint"""
data = []
_VarintEncoder()(data.append, value, False)
return b"".join(data)
def decode_varint(data):
"""Decode a protobuf varint to an int"""
return _DecodeVarint(data, 0)[0]
def decode_string(data):
"""Decode a string: its length as a varint, then its UTF-8 bytes"""
size, position = _DecodeVarint(data, 0)
return data[position : position + size].decode("utf-8")
def send_message(conn, msg):
"""Send a message, prefixed with its size, to a TCP/IP socket"""
data = msg.SerializeToString()
size = encode_varint(len(data))
conn.sendall(size + data)
def recv_message(conn):
"""Receive a Message, prefixed with its size, from a TCP/IP socket"""
# Receive the size of the message data
data = b""
while True:
try:
data += conn.recv(1)
size = decode_varint(data)
break
except IndexError:
pass
# Receive the message data
data = b""
while len(data) < size:
data += conn.recv(size - len(data))
# Decode the message
msg = KRPC.Message()
msg.ParseFromString(data)
return msg
Connecting#
Open a TCP socket to the server’s address and port, which default to 127.0.0.1 and 50000.
Then send the connection handshake. The connection
carries the requests, the responses and the stream updates until either side sends a
disconnect.
Examples#
Note
These examples show the protocol, and omit much of the behavior a client library needs, such as handling errors and failed connections. A client library should implement the client specification in its entirety.
The following script connects to the server with the name “Example”, calls KRPC.GetStatus and
prints the server version. It then ends the connection:
import socket
from google.protobuf.internal.decoder import _DecodeVarint
from google.protobuf.internal.encoder import _VarintEncoder
from krpc.schema import KRPC_pb2 as KRPC
def encode_varint(value):
"""Encode an int as a protobuf varint"""
data = []
_VarintEncoder()(data.append, value, False)
return b"".join(data)
def decode_varint(data):
"""Decode a protobuf varint to an int"""
return _DecodeVarint(data, 0)[0]
def decode_string(data):
"""Decode a string: its length as a varint, then its UTF-8 bytes"""
size, position = _DecodeVarint(data, 0)
return data[position : position + size].decode("utf-8")
def send_message(conn, msg):
"""Send a message, prefixed with its size, to a TCP/IP socket"""
data = msg.SerializeToString()
size = encode_varint(len(data))
conn.sendall(size + data)
def recv_message(conn):
"""Receive a Message, prefixed with its size, from a TCP/IP socket"""
# Receive the size of the message data
data = b""
while True:
try:
data += conn.recv(1)
size = decode_varint(data)
break
except IndexError:
pass
# Receive the message data
data = b""
while len(data) < size:
data += conn.recv(size - len(data))
# Decode the message
msg = KRPC.Message()
msg.ParseFromString(data)
return msg
# Open a TCP/IP socket to the server
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.connect(("127.0.0.1", 50000))
# Send a connection request
message = KRPC.Message()
message.connection_request.protocol_version = 2
message.connection_request.client_name = "Example"
send_message(conn, message)
# Receive the connection response
response = recv_message(conn).connection_response
# Check the connection was successful
if response.status != KRPC.ConnectionResponse.OK:
raise RuntimeError("Connection failed: " + response.message)
if response.protocol_version != 2:
raise RuntimeError("The server does not support protocol version 2")
print("Connected to the server")
# Invoke the KRPC.GetStatus RPC, in a request with the id 1
message = KRPC.Message()
message.request.id = 1
call = message.request.calls.add()
call.service = "KRPC"
call.procedure = "GetStatus"
send_message(conn, message)
# Receive the response, which carries the id of the request it answers
response = recv_message(conn).response
assert response.id == 1
# Check for an error in the response
if response.HasField("error"):
raise RuntimeError("ERROR: " + str(response.error))
# Check for an error in the results
assert len(response.results) == 1
if response.results[0].HasField("error"):
raise RuntimeError("ERROR: " + str(response.results[0].error))
# Decode the return value, a ServerStatus structure sent as a Tuple of its
# fields
status = KRPC.Tuple.FromString(response.results[0].value)
# Print out the server version, the first field
print(decode_string(status.items[0]))
# End the connection with a disconnect, then close the write side
disconnect = KRPC.Disconnect(reason=KRPC.Disconnect.CLOSED)
send_message(conn, KRPC.Message(disconnect=disconnect))
conn.shutdown(socket.SHUT_WR)
# Discard anything still arriving until the server closes its side, or a
# second passes with nothing
conn.settimeout(1)
try:
while conn.recv(4096):
pass
except TimeoutError:
pass
conn.close()
The following script adds a stream, then receives its updates on the same connection:
import socket
from google.protobuf.internal.decoder import _DecodeVarint
from google.protobuf.internal.encoder import _VarintEncoder
from krpc.schema import KRPC_pb2 as KRPC
def encode_varint(value):
"""Encode an int as a protobuf varint"""
data = []
_VarintEncoder()(data.append, value, False)
return b"".join(data)
def decode_varint(data):
"""Decode a protobuf varint to an int"""
return _DecodeVarint(data, 0)[0]
def send_message(conn, msg):
"""Send a message, prefixed with its size, to a TCP/IP socket"""
data = msg.SerializeToString()
size = encode_varint(len(data))
conn.sendall(size + data)
def recv_message(conn):
"""Receive a Message, prefixed with its size, from a TCP/IP socket"""
# Receive the size of the message data
data = b""
while True:
try:
data += conn.recv(1)
size = decode_varint(data)
break
except IndexError:
pass
# Receive the message data
data = b""
while len(data) < size:
data += conn.recv(size - len(data))
# Decode the message
msg = KRPC.Message()
msg.ParseFromString(data)
return msg
# Open a TCP/IP socket to the server
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.connect(("127.0.0.1", 50000))
# Send a connection request
message = KRPC.Message()
message.connection_request.protocol_version = 2
message.connection_request.client_name = "Example"
send_message(conn, message)
# Receive the connection response
response = recv_message(conn).connection_response
# Check the connection was successful
if response.status != KRPC.ConnectionResponse.OK:
raise RuntimeError("Connection failed: " + response.message)
if response.protocol_version != 2:
raise RuntimeError("The server does not support protocol version 2")
print("Connected to the server")
# Build a KRPC.GetStatus call to be streamed
stream_call = KRPC.ProcedureCall()
stream_call.service = "KRPC"
stream_call.procedure = "GetStatus"
# Call KRPC.AddStream to add the stream, in a request with the id 1
message = KRPC.Message()
message.request.id = 1
call = message.request.calls.add()
call.service = "KRPC"
call.procedure = "AddStream"
call.arguments.add(position=0, value=stream_call.SerializeToString())
send_message(conn, message)
# Receive the response, which carries the id of the request it answers. The
# stream's first update follows it.
response = recv_message(conn).response
assert response.id == 1
# Check for an error in the response
if response.HasField("error"):
raise RuntimeError("ERROR: " + str(response.error))
# Check for an error in the results
assert len(response.results) == 1
if response.results[0].HasField("error"):
raise RuntimeError("ERROR: " + str(response.results[0].error))
# Decode the return value, which is the stream id as a uint64
stream_id = decode_varint(response.results[0].value)
# Repeatedly receive stream updates, which arrive on the same connection
while True:
update = recv_message(conn).stream_update
assert len(update.results) == 1
assert stream_id == update.results[0].id
# Decode the return value, a ServerStatus structure sent as a Tuple of
# its fields. Its fourth field is the server statistics, another
# structure, whose second field is the number of bytes the server has
# written.
status = KRPC.Tuple.FromString(update.results[0].result.value)
statistics = KRPC.Tuple.FromString(status.items[3])
print(decode_varint(statistics.items[1]))