Source

asyncplot / asyncplot / client.py

Full commit
r"""Example computation Client."""
import cPickle
import time
import socket

from matplotlib import pyplot as plt

import threading_server
import server


class Client(object):
    def __init__(self, Plot,
                 host=server.PlotSocketServer._HOST,
                 port=server.PlotSocketServer._PORT):
        self.host = host
        self.port = port
        self.plot = Plot()
        self.plot.plt.clf()
        self._BUF_SIZE = 200

    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(threading_server.Plot):
        def draw(self, x, y):
            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()