Last active
November 6, 2023 22:55
-
-
Save miceno/2a0df069dca1e1645a7dd9aeefe67c6b to your computer and use it in GitHub Desktop.
TCP persistent socket client to send text messages from terminal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# | |
# Python script to send text messages over a TCP socket. | |
# Copyright 2023 | |
# by Orestes Sanchez Benavente is licensed under CC BY-NC-SA 4.0. | |
# | |
# | |
# Script to send text messages over a TCP socket. | |
# It creates a connection to the server and it keeps it | |
# for the whole session. | |
# | |
# The code is a bit around the SnapCap and Rolloffino protocol. | |
# | |
# Author: Orestes Sanchez-Benavente <miceno.atreides@gmail.com> | |
# | |
import socket | |
import time | |
import errno | |
import argparse | |
def plain_loop(s): | |
while True: | |
data = input("Please enter the message: ") | |
if 'Exit' == data: | |
break | |
print(f'Processing Message from input() *****{data}*****') | |
s.send(data.encode('ascii', 'ignore')) | |
data = s.recv(1024).decode() | |
print('Received', repr(data)) | |
def wait_for_all_loop(s, opts): | |
s.settimeout(0.5) | |
s.setblocking(True) | |
while True: | |
data = input("Please enter the message: ") | |
if 'Exit' == data: | |
break | |
if opts.newline: | |
print("add new line") | |
data += "\n" | |
print(f'Processing Message *****{data!r}*****') | |
s.send(data.encode('ascii', 'ignore')) | |
# time.sleep(1) | |
run_main_loop = True | |
while run_main_loop: | |
# The socket have data ready to be received | |
data = '' | |
continue_recv = True | |
while continue_recv: | |
# Try to receive som data | |
data += s.recv(1024).decode() | |
continue_recv = not ('\n' in data and ')' in data) | |
# print(f"data={data}\n") | |
run_main_loop = not ('\n' in data and ')' in data) | |
# print(f"run_main_loop={run_main_loop}\n") | |
print(F'Received *****{data!r}*****') | |
def init_argparse() -> argparse.ArgumentParser: | |
parser = argparse.ArgumentParser( | |
description="Send and receive TCP messages over a persistent server connection." | |
) | |
parser.add_argument( | |
"-s", "--server", default="localhost", | |
help="Server host" | |
) | |
parser.add_argument( | |
"-n", "--newline", action="store_true", default=False, | |
help="Add a new line to every request" | |
) | |
parser.add_argument( | |
"-p", "--port", type=int, default=8888, | |
help="Server port" | |
) | |
return parser | |
if __name__ == '__main__': | |
parser = init_argparse() | |
args = parser.parse_args() | |
s = socket.create_connection((args.server, args.port), ) | |
wait_for_all_loop(s, args) | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment