#!/usr/bin/env python
# TCP client
'''
Python TCP client demo

DISCLAIMER: USE CODE AT YOUR OWN RISK!
!!! OPENS _HUGE_ SECURITY HOLE !!!
* work in progress
* no functional error handling, client disconnecting, etc.
* world read and writable ports

2015-03-05 - Michael Hartl <hartl@mpe.mpg.de>

Usage: tcpclt <host> <port>
'''

print __doc__

import socket as soc
import sys

NBUF = 1024
# clt = None

# Send data
def clt_send(dat):
    global clt
    clt.send(str(dat)+'\0')
    clt.setblocking(1)
    ret = ''
    try:
        ret = clt.recv(NBUF)
    except (StandardError):
        None
    if (ret != repr('\0')):
        raise RuntimeError("Error: "+ret)

# Request data
def clt_requ(req):
    global clt
    clt.send(str('srv_send('+req+')\0'))
    clt.setblocking(1)
    dat = clt.recv(NBUF)
    while (dat[-6:] != repr('\0')):
        ret = clt.recv(NBUF)
        if (ret == ''):
            raise RuntimeError("Error: socket connection broken")
        dat = dat+ret
    return dat[0:-6]

# Connect
def clt_open(host, port):
    global clt
    clt = soc.socket(soc.AF_INET, soc.SOCK_STREAM)
    clt.connect((host, port))

# Disconnect
def clt_close():
    global clt
    clt.close()

if __name__ == '__main__':
    
    # Prog ID, hostname, and port
    prog = str(sys.argv[0])
    host = str(sys.argv[1])         # localhost
    port = int(sys.argv[2])         # port

    clt_open(host, port)

    if eval(clt_requ('sys.platform == "win32"')) == True:
        clt_send('import win32com.client as com')
        clt_send('xl = com.DispatchEx("Excel.Application")')
        clt_send('xl.Visible = 1')
        clt_send('wb = xl.Workbooks.Add()')
        clt_send('sh = wb.ActiveSheet')
        clt_send('sh.Cells(1,1).Value = 7')
        clt_send('sh.Cells(1,2).Value = 9')
        clt_send('sh.Cells(1,3).Value = 11')
        clt_send('sh.Cells(2,1).Value = "=Sum(A1:C1)"')
        print clt_requ('sh.Cells(2,1).Value')
    else:
        import numpy as np
        clt_send('import numpy as np')
        clt_send('a = np.array([[1,2,3],[4,5,6],[7,8,9]])')
        clt_send('b = np.array([1,2,3])')
        clt_send('c = a*b')
        ans = clt_requ('c')
        c = eval('np.'+ans.replace('\n',''))
        print c
    clt_close()
