Source

asyncplot / asyncplot / client.py

r"""Example computation Client."""
import cPickle
import socket

_CLIENTCOMMAND = """
import cPickle
import asyncplot.client
Plotter = cPickle.loads(%(Plotter)s)
c = asyncplot.client.Client(Plotter=Plotter, host=%(host)s, port=%(port)i)
c.run()
"""


class Client(object):

    client_command = _CLIENTCOMMAND

    def __init__(self, Plotter, host=None, port=None):
        import server
        if host is None:
            host = server.PlotSocketServer._HOST
        if port is None:
            port = server.PlotSocketServer._PORT
        self.host = host
        self.port = port
        self.plot = Plotter()
        self._BUF_SIZE = 2**12

    def get_data(self):
        sock = self.connect()
        datasz = -1
        data = []
        while datasz != 0:
            data.append(sock.recv(self._BUF_SIZE))
            datasz = len(data[-1])
            #print "tmpdata from Server is %i bytes long." % (datasz,)

        #print "close client socket and shutdown. "
        sock.close()
        #sock.shutdown(1)

        return ''.join(data)

    def connect(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #print "Trying to connect to port %i..." % (self.port,)
        sock.connect((self.host, self.port))
        #print "Connected to port %i." % (self.port,)
        return sock
        
    def run(self):
        while True:
            data = self.get_data()
            v, kw = cPickle.loads(data)
            self.plot.draw(*v, **kw)


def run_client():
    #create the Client instance and pass the Plot object, then call
    #run().
    class Plot(object):
        def __init__(self):
            from matplotlib import pyplot as plt
            self.plt = plt

        def draw(self, x, y):
            plt = self.plt
            plt.ioff()
            plt.clf()
            plt.plot(x, y)
            #print y
            plt.ion()
            plt.draw()
            #time.sleep(0.5)     # Pretend this is slow

    c = Client(Plot=Plot)
    #raw_input('adjust plot and press return')
    c.run()


if __name__ == "__main__":
    run_client()