0

In most console and IRC applications, the user can make inputs while the console is also making outputs. Is this possible in python? and if so, how? I am trying to make an IRC-like application and I have tried using multiple threads at once, but the input is never fully registered. I have made the server repeat a message every couple of seconds for testing purposes.

Here is the code for the client:

import socket
import threading

TARGET_IP = socket.gethostname()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #create socket object using IPV4 and TCP respectively

def utf8len(a):
    return len(a.encode('utf-8')) #returns length of string in unicode

def recievethread():
    while True:
        full_msg = ''
        msg = s.recv(1024) #waits to recieve message
        full_msg += msg.decode("utf-8") #decode
        print(full_msg) #print
        
def inputthread():
    while True: #input loop
        inp = input()
        print("[DEBUG] - {inp}")
        if inp == "!04exit":
            recieving.exit()
            print("[CLIENT] - Closing connection to {TARGET_IP}!")
            break #safely close the client with all threads
        
        if utf8len(inp) < 1024:
            pass
        else:
            print("[CLIENT] - message is too long!")

s.connect((TARGET_IP, 1432)) #establish connection on the same machine for now

recieving = threading.Thread(target=recievethread)
recieving.start()
inputloop = threading.Thread(target=inputthread)
inputloop.start()

And this is what happens when I try to make an input while the server is running:

$ python client.py                                                
Welcome to the Server!
This is a timed message!
Trying This is a timed message!
to type This is a timed message!
an This is a timed message!
input wiThis is a timed message!
thoutThis is a timed message!
 pressing enThis is a timed message!
ter
Exception in thread Thread-2:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "client.py", line 30, in inputthread
    inp = input()
  File "<string>", line 1
    Trying to type an input without pressing enter
            ^
SyntaxError: invalid syntax

This is a timed message!
This is a timed message!
  • Also with `print("[DEBUG] - {inp}")` you probably meant `print(f"[DEBUG] - {inp}")` (note the `f` prefix) and the other strings you used `{}` as well – Tomerikoo May 06 '21 at 10:13
  • you probably want some TUI (text user interface) library to get the console looking nice. the standard low-level interface is [curses](https://docs.python.org/3/library/curses.html) but it would take a lot of code to make behave like a "nice" interactive console app – Sam Mason May 06 '21 at 14:19

0 Answers0