PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 15, 2022

[FIXED] How to print while waiting for input?

 September 15, 2022     client, multithreading, printing, python     No comments   

Issue

def receivedata(self):
    while True:
        data = self.soc.recv(1024)
        if data != "" or data != '' or data != "":
            sys.stdout.write("Recv>> ")
            sys.stdout.write(data)
            sys.stdout.flush()
            if data == "Server Shutdown":
                self.soc.close()
        elif not data:
            continue
def senddata(self):
    while True:
        try:
            sys.stdout.write("Send>> ")
            msg = sys.stdin.readline()
            self.soc.send(msg)
        except socket.error:
            sys.stdout.write("Socket Connection Timed Out")

This is part of my client code of python, and what I expect from this is while this waits for user input, it prints what it receives from server.

However, client does not print anything when it is waiting for user input — it only prints when something has been entered by user.

Is there a way that I could change this so that it prints even when it is waiting for user input?


Solution

If your program needs to wait on 2 separate events (user input and incoming socket data), you'll have to use threads, something like:

recv_thread = threading.Thread(target=receivedata)
recv_thread.setDaemon(True)
recv_thread.start()
senddata()

Couple of things about the code:

  • when socket.error is encountered it can be something other than timeout.
  • at one point you will need to exit the while loop from senddata (when the user input a certain text? or) in case of exception.
  • also add exception handling in receivedata
  • if statement in receivedata is not OK. you could replace it to:

    if data:
        ...if statements...
    


Answered By - CristiFati
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing