From d4d03e2f6c495858faeb1560754a6f34a62e76d1 Mon Sep 17 00:00:00 2001 From: troido Date: Thu, 24 Jan 2019 18:39:20 +0100 Subject: git repo for rust version of asciifarm --- client.py | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100755 client.py (limited to 'client.py') diff --git a/client.py b/client.py new file mode 100755 index 0000000..f1f6867 --- /dev/null +++ b/client.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 + +import socket +import sys +import threading +import json +import getpass + + +def send(sock, msg): + length = len(msg) + header = length.to_bytes(4, byteorder="big") + totalmsg = header + msg + sock.sendall(totalmsg) + +def receive(sock): + header = recvall(sock, 4) #sock.recv(4) + length = int.from_bytes(header, byteorder="big") + return recvall(sock, length) + +def recvall(sock, length): + chunks = [] + bytes_recd = 0 + while bytes_recd < length: + chunk = sock.recv(min(length - bytes_recd, 4096)) + if chunk == b'': + break + #raise RuntimeError("socket connection broken") + chunks.append(chunk) + bytes_recd = bytes_recd + len(chunk) + return b''.join(chunks) + + + +sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) +sock.connect("\0rustifarm")#("localhost", 1234)) + +def listen(): + while True: + d = receive(sock) + if len(d) == 0: + print("Connection closed by server", file=sys.stdout) + return + print(str(d, "utf-8")) + +threading.Thread(target=listen, daemon=True).start() + +if len(sys.argv) >= 2: + name = sys.argv[1] +else: + name = "~" + getpass.getuser() + +send(sock, bytes(json.dumps(["name", name]), "utf-8")) + +for line in sys.stdin: + send(sock, bytes(json.dumps(["chat", line.strip()]), "utf-8")) -- cgit