Skip to content

Instantly share code, notes, and snippets.

@FSX
Created October 16, 2010 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FSX/629770 to your computer and use it in GitHub Desktop.
Save FSX/629770 to your computer and use it in GitHub Desktop.
A simple client for the Evennia MUX server.
# -*- coding: utf-8 -*-
"""
evenniaclient
~~~~~~~~~~~~~
A simple client for the Evennia MUX server.
Website: http://evennia.com/
"""
import sys
import socket
import readline # For line editing
from thread import start_new_thread
#: The amount of data the socket reads from the socket in bytes.
read_buffer_size = 4096
class EvenniaClient(object):
"""A simple CLI client for Evennia, a MUX server.
:param host: The hostname of the server.
:param port: The port of the server.
"""
#: ``socket`` is ``None`` of there's no connection. When there is a
#: connection it contains a ``socket._socketobject`` object.
socket = None
def __init__(self, host, port):
self.host = host
self.port = port
def connect(self):
"""Creates a connection with the MUX server and start the main loop.
"""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((self.host, self.port))
self._loop()
def disconnect(self):
"""Sends a quit message to the server, closes the connection, destroys
the socket and exists the program.
"""
self._send('quit')
print '\n%s\x1b[0m' % self.socket.recv(read_buffer_size)
#self.socket.close()
self.socket = None
sys.exit()
def _read_all(self):
"""Starts a loop and reads data from the socket as long as the socket
exists. If the socket is destroyed this method automatically stops
reading.
"""
while self.socket:
data = self.socket.recv(read_buffer_size)
# \x1b[0m is used to reset the font color after a colorized
# message has been printed.
print '%s\x1b[0m' % data.strip()
if data == '':
return self.disconnect()
def _send(self, text):
"""Send a message to the server.
:param text: The text that is send to the server.
"""
if self.socket:
self.socket.send('%s\n' % text)
def _loop(self):
"""Starts the read loop, the method that read data from the socket, and
the write loop, which reads data from STDIN and sends it to the server.
"""
try:
# The read loop is started in a thread to prevent it from blocking
# the whole process while waiting for data.
start_new_thread(self._read_all, ())
while self.socket:
self._send(raw_input())
except KeyboardInterrupt:
self.disconnect()
if __name__ == '__main__':
try:
host = sys.argv[1]
port = int(sys.argv[2])
except IndexError:
print 'A hostname and port must be provided!'
print 'Usage: evenniaclient.py localhost 4000'
sys.exit()
c = EvenniaClient(host, port)
c.connect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment