server - (Python) How can I receive messages in real-time without refreshing? -
i have followed tutorial youtuber under name of drapstv. tutorial made in python 2.7 , makes networked chat using udp. converted python 3 , got work. however, way threading setup have send message(or press enter, blank message) refresh , receive messages other clients. here video incase may need it: https://www.youtube.com/watch?v=pkfwx6rjrai
and here server code:
from socket import * import time address = input("ip address: ") port = input("port: ") clients = [] serversock = socket(af_inet, sock_dgram) serversock.bind((address, int(port))) serversock.setblocking(0) quitting = false print("server , running far.") while not quitting: try: data, addr = serversock.recvfrom(1024) if "quit" in str(data): quitting = true if addr not in clients: clients.append(addr) print(time.ctime(time.time()) + str(addr) + ": :" + str(data.decode())) client in clients: serversock.sendto(data, client) except: pass serversock.close()
here client code:
from socket import * import threading import time tlock = threading.lock() shutdown = false def receiving(name, sock): while not shutdown: try: tlock.acquire() while true: data, addr = sock.recvfrom(1024) print(str(data.decode())) except: pass finally: tlock.release() address = input("ip address: ") port = 0 server = address, 6090 clientsock = socket(af_inet, sock_dgram) clientsock.setsockopt(sol_socket, so_reuseaddr, 1) clientsock.bind((address, int(port))) clientsock.setblocking(0) rt = threading.thread(target=receiving, args=("recvthread", clientsock)) rt.start() nick = input("how nickname: ") message = input(nick + "> ").encode() while message != "q": if message != "": clientsock.sendto(nick.encode() + "> ".encode() + message, server) tlock.acquire() message = input(nick + "> ").encode() tlock.release() time.sleep(0.2) shutdown = true rt.join() clientsock.close()
@furas has kindly explained issue me: not receiving methods flawed(such threading or functions), input call preventing client not receiving anything. so, in order fix this, or else having issue needs find way call input when button pressed unless typing, can receive messages or data.
thank @furas! https://stackoverflow.com/users/1832058/furas
Comments
Post a Comment