-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtcp-client
More file actions
executable file
·89 lines (75 loc) · 2.53 KB
/
Copy pathtcp-client
File metadata and controls
executable file
·89 lines (75 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env python
from __future__ import print_function
import socket
try:
import readline
except ImportError:
# don't need readline on windows
pass
# A little annoyance from Python2/Python3: raw_input got renamed. This
# nastiness is needed for Python2 backward compatibility.
try:
input = raw_input
except NameError:
pass
# Checks whether the server will interpret cmd as a table command: search for
# first of '?', '=', '<', if '<' found first then it's a table command.
def is_table_command(cmd):
for ch in cmd:
if ch in '?=':
return False
if ch == '<':
return True
return False
class Client(object):
def __init__(self, hostname, port):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.connect((hostname, port))
self.s.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
self.line_iter = self.get_lines()
try:
self.run()
except (EOFError, KeyboardInterrupt) as blah:
pass
finally:
self.s.shutdown(socket.SHUT_WR)
self.s.close()
def get_lines(self):
buf = ""
while True:
lines = buf.split("\n")
for line in lines[:-1]:
yield line
buf = lines[-1]
# Get something new from the socket
rx = self.s.recv(4096).decode()
assert rx, "Didn't get response in time"
buf += rx
def recv_all(self):
ret = [next(self.line_iter)]
assert ret[0], "Connection closed"
if ret[0].startswith("!"):
while not ret[-1].startswith("."):
ret.append(next(self.line_iter))
return ret
def prompt_and_send(self):
msg = input("< ")
self.s.sendall((msg + "\n").encode())
return msg
def run(self):
while True:
msg = self.prompt_and_send()
if is_table_command(msg):
while msg:
msg = self.prompt_and_send()
for resp in self.recv_all():
print("> %s" % resp)
from argparse import ArgumentParser
parser = ArgumentParser(
description="Commandline client to PandA TCP server")
parser.add_argument("hostname", default="localhost", nargs="?",
help="Hostname of PandA box (default localhost)")
parser.add_argument("port", type=int, default=8888, nargs="?",
help="Port number of TCP server (default 8888)")
args = parser.parse_args()
Client(args.hostname, args.port)