The problem is that my chat client must receive and print data from the server when the server sends it, and then allows the client to respond.
This works great, except that the whole process stops when the client is prompted to respond. Thus, messages are accumulated until you print something, and after that you can print all received messages.
I donβt know how to fix this , so I decided why the client does not have time to enter the response timeout after 5 seconds so that the answers can go regardless . This is pretty wrong, because the input will reset itself, but it works better anyway.
Here is the function that should have a timeout:
def outgoing():
global out_buffer
while 1:
user_input=input("your message: ")+"\n"
if user_input:
out_buffer += [user_input.encode()]
s.send(out_buffer[0])
out_buffer = []
How do I use a timeout? I thought to use time.sleep, but that just pauses the whole operation.
I tried looking for documentation. But I did not find anything that would help me make the program counted to a certain limit, and then continue.
Any idea on how to solve this? (No need to use the timeout, just need to stop the message overlay before the clients reply is sent) (Thanks to everyone who helped me get to this)
For Ionut Hulub:
from socket import *
import threading
import json
import select
import signal
print("client")
HOST = input("connect to: ")
PORT = int(input("on port: "))
s = socket(AF_INET, SOCK_STREAM)
s.connect((HOST, PORT))
print("connected to:", HOST)
out_buffer = []
def incoming():
rlist,wlist,xlist = select.select([s], out_buffer, [])
while 1:
for i in rlist:
data = i.recv(1024)
if data:
print("\nreceived:", data.decode())
def outgoing():
global out_buffer
while 1:
user_input=input("your message: ")+"\n"
if user_input:
out_buffer += [user_input.encode()]
s.send(out_buffer[0])
out_buffer = []
thread_in = threading.Thread(target=incoming, args=())
thread_out = threading.Thread(target=outgoing, args=())
thread_in.start()
thread_out.start()
thread_in.join()
thread_out.join()