Q:

How to turn a string's length into a byte?

I'm trying to make a client to connect to a chat server that's running erlang, which parses everything as bytes. I can connect to the server successfully.
However, the server administrator keeps telling me I'm getting my format wrong. I think I have things finally nailed down, but I come across an unusual issue; when I try to convert the length of the message's contents, it comes out horribly incorrect (the closest I got was with hex, and it still turned out as "31" which is over 30 characters off too long).
Here is my code:
import socket
import struct
import binascii
host = 'jimmyr.com'    # The remote host
port = 12345              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send('\x00\x01\x00\x00\x00\x04Omio') # This works.
data = s.recv(1024)
print repr(data)+"\n" # From server, I get '\x00\x01\x00\x0eYou connected!'
message = raw_input("Message to send at chat [!!! to quit]")
mlength = str(len(message))
print repr(data)+"\n"
while str(message) != "!!!":
    if str(message) != "":
        s.send('\x00\x01\x00\x01'+(str(len(message)).encode("hex")+str(message).encode("hex")))
        message = raw_input("Message to send to chat [!!! to quit]")
        data = s.recv(1024)
        print repr(data)+"\n"
    else:
    print repr(data)+"\n"
#EoF

In terms of what response I need to make, please see the server's protocol specification.

A:

I think you're misunderstanding what the hex representations in the specification mean. The spec uses hex to show binary values. The key line is Everything non-text will be 2 byte long. So, your message length needs to be encoded as a two-byte (big-endian) binary value. You don't want your string to be encoded in hex either, but rather to send it as a plain bytestring.
I think you want to send this:
struct.pack(">HHH", 1, 1, len(message)) + message

This uses struct.pack to handle the "server ID" and "packet code" numbers as well as the length, which should be rather nicer than needing to encode those other bits by hand. The > code means to use big-endian encoding, and the three Hs say to pack up three "unsigned short" (two-byte) integers.

