TCP connection is not giving me output second time - python-3.x

I have made server/client with TCP connection, which converts bin to dec or dec to bin and returns the output to the client. The program is running fine with one iteration
Problem
When I want to get the output(conversion) again without quitting the program, I enter a number and it sends that number to the server, the server doesn't responds back, the cursor starts blinking and shows no output. I waited for like 5 min and nothing happened.
I don't understand why this is happening
PS: pardon my code, I know it can be improved. I just want it to show output again and again
Here's my code. Assume all libraries are imported and all conversion functions are running fine and included
SERVER
print('The server is ready')
message = "yes"
connectionSocket, addr = serverSocket.accept()
while 1:
while(message == "yes"):
print(connectionSocket.getpeername())
sentence = connectionSocket.recv(4096).decode('utf-8')
number = connectionSocket.recv(4096).decode('utf-8')
# binary to decimal conversion
if(sentence == 'bin_to_dec'):
digits = str(binToDec(number))
connectionSocket.send(digits.encode('utf-8'))
# decimal to binary conversion
elif(sentence == 'dec_to_bin'):
numbers = str(decToBin(number))
connectionSocket.send(numbers.encode('utf-8'))
# If everything fails
else:
print("Wrong input!")
connectionSocket.close()
if(connectionSocket.recv(4096).decode('utf-8') == "no"):
break
connectionSocket.close()
Client
clientSocket.connect((serverName, serverPort))
# flag to check if the user wants to end the input
end_everything = False
again = 'yes'
while(end_everything == False):
# while the user wants to input again
while(again.lower() == "yes"):
# input
sentence = str(input('bin_to_dec or dec_to_bin >: '))
# checking whether the input is correct
if(sentence.lower() == "bin_to_dec" or sentence.lower() == "dec_to_bin"):
# inputting the number to convert
number = str(input("which number or digits you want to convert >: "))
#encodes the input and sends it to the server
clientSocket.send(sentence.encode('utf-8'))
clientSocket.send(number.encode('utf-8'))
#resonse from the server
modifiedSentence = clientSocket.recv(4096)
response = modifiedSentence.decode('utf-8')
#prints that response
print('From Server: ', response)
#prompting user, if they want to input again
message = input("type 'yes' or 'no' if you want to input again: ")
if(message.lower() == "yes"):
#clientSocket.send(message.encode())
continue
elif(message.lower() == "no"):
clientSocket.send(message.encode('utf-8'))
again = 'no'
else:
print("Please enter correct input")
else:
print("Not valid input!")
break
clientSocket.close()

So first of all, yes, your close is a little rough. It's actually a little difficult to follow, mainly because I'm not as used to python probably. "while 1" always hurts, but I do it too.
So, my first guess is the "serverSocket.accept()" call on the server. It looks like you accept a connection, receive data, send, and then loop around and accept a new connection. Client side expects to keep sendings messages over and over.
You probably want that serverSocket.accept() moved to the outside while loop instead, so it keeps reading from your connection until it closes down.

Related

cant get my while loops working the way i want it to

i am trying to get this code to work properly where if you input a number it will revert you back to the name=input prompt and once you enter alphabetical characters and not numerical characters it will allow you to move on to the next set of code but it keeps returning you to the name = input and doesnt let you through the rest of the code
def setup():
global name
global HP
global SP
global MP
while True:
try:
name = input('can you please tell me your name? ')
name2=int(name)
if not name.isalpha==True and not name2.isdigit==False:
break
except Exception:
print('please input your name')
continue
HP = randint(17,20)
SP = randint(17,20)
MP = randint(17,20)
print('welcome ['+name+':]: to the moon landing expedition')
There is a problem at name2=int(name) This causes an exception unless you type all numbers. In turn, this triggers the Exception and loops it forever. Your while loop seems fine.
What i think you should do:
while True:
name = input('What is your name')
isnum = False
for i in name:
if i.isnumeric():
isnum = True
break
if isnum:
print('Please type your name.')
continue
break

Python: Printing data and receiving user input simultaneously

I want to be able to receive user input and print stuff simultaneously, without them interfering. Ideally, that would be printing regularly and having the user type input to the bottom of the terminal window, for example:
printed line
printed line
printed line
printed line
printed line
(this is where the next print would happen)
Enter Input: writing a new input...
This should look like a chat app or something of that sort.
If there is no good way to do that, any way to print above the input line would be amazing too.
Thanks!
Sadly it is not very feasible to both take input and give output in python, without importing modules to directly interact with the OS.
But you can can get pretty close to it with this code:
import curses
import random # for random messages
#this should be async
def get_message():
message = [str(random.randint(0,9)) for i in range(15)]
return "".join(message)
def handle_command(cmd): # handle commands
if cmd=="exit":
exit(0)
def handle_message(msg): # send a message
raise NotImplementedError
def draw_menu(stdscr):
stdscr.erase()
stdscr.refresh()
curses.raw()
k = 0
typed=""
while True:
# Initialization
stdscr.erase()
height, width = stdscr.getmaxyx()
stdscr.addstr(0, 0, "Welcome to chat app")
msg = get_message()
if msg: # add a message if it exists
stdscr.addstr(1, 0, msg)
if k==ord("\n"): # submit on enter
if typed.startswith("/"): # execute a command
typed = typed[1:]
handle_command(typed)
elif typed.startswith("./"): # bypass commands with a dot
typed = typed[1:]
handle_message(typed)
else:
handle_message(typed) # send the message
typed = ""
elif k==263: # Backspace
typed = typed[:-1] # erase last character
stdscr.addstr(height-1, 0, typed)
elif k==3: # Ctr+C
typed="" # Delete the whole string
stdscr.addstr(height-1, 0, typed)
elif k!=0:
typed += chr(k) # add the char to the string
stdscr.addstr(height-1, 0, typed)
stdscr.refresh() # refresh
# Wait for next input
k = stdscr.getch()
def main():
curses.wrapper(draw_menu)
if __name__ == "__main__": # dont import
main()
the only thing that is to do to update the messages is to type a new char.
And I do not recommend you to build a chat in the terminal for anything other then educational value (trust me I tried it).
It would be better if you tried it using a web platform (e.g. Tauri or Electron)
Also the code cannot:
insert automatic line breaks (it errors)
send any messages (must implement yourself)
show any user names (must implement yourself)

How to communicate two python files so one prints just before the other reads though the console (interactive)

what I want is something like this:
The first file just prints as soon as the 2nd has read
# a.py
print('pepe')
# wait till the other had read
print(23)
The second program uses data from the later
# b.py
name = input()
age = int(input())
print('Hi ' + name + ', you are ' str(age))
So I can see in the console:
Hi pepe, you are 23
I want to do this because, I waste a lot of time typing in the console. And I want to do it automatically.
Just in case, I browsed for this thing a long time, but no idea, that is why I decided to ask here.
A couple of different ways.
1) while True:
an infinite loop that requires you to use some sort of
while True:
cmd = input("type something")
if cmd == 'e':
do something
elif cmd == 'f':
do something else
else:
do that last thing
2) input("press enter to continue")
input('press enter to continue')
Hopefully that gets you what you need...
You can also learn more here: How do I make python to wait for a pressed key

Defining function difficulties ["NameError: name 'number' is not defined"]

Okay, trying to make a simple game of Guessing Numbers but I can't find the mistake in this code. Still pretty new to python so probably the reason why but I can't figure out what is wrong with it.
import random
from time import sleep
def start():
print("Welcome To The Guessing Game \n Try to guess the number I'm thinking of \n Good luck!")
selectRandomNumber()
guessCheck(number, numberInput=1)
def restart():
print("Creating new number ...")
sleep(1)
print("OK")
selectRandomNumber()
guessCheck(number,numberInput=1)
def selectRandomNumber():
number = random.randint(0,1000)
tries = 0
return
def tryAgain():
while True:
try:
again = int(input("Do you want to play again? y/n:"))
except ValueError:
print("Couldn't understand what you tried to say")
continue
if again == "y" or "yes":
print("Awesome! Lets go")
restart()
elif again == 'n' or "no":
print("Goodbye!")
break
else:
print("Not a valid option")
continue
def guessCheck(number,numberInput=1):
while True:
try:
numberInput = int(input("What number do you think it is?: "))
except ValueError:
print("Couldn't understand that. Try again")
continue
if numberInput > number:
print("Too high")
tries += 1
continue
elif numberInput < number:
print("Too low")
tries += 1
continue
elif numberInput == number:
print("Congrats! You got my number")
tryAgain()
number = selectRandomNumber()
print(number)
start()
Every time I try to run the program I keep getting the same mistake.
It tells me:
Traceback (most recent call last):
File "python", line 60, in <module>
start()
File "python", line 8, in start
guessCheck(number, numberInput)
NameError: name 'number' is not defined
Don't quite understand what that means.
Some help would be appreciated. Thanks!
* UPDATE *
Was able to fix the part about defining the variable but now new problem happened where when I try to run
Same code as before but added
guessCheck(number,numberInput=1)
and also added the variable number at the end
number = selectRandomNumber()
print(number)
start()
when I run it I get this
None # this is from `print(number)` so instead of getting a number here I'm getting `None`
Welcome To The Guessing Game
Try to guess the number I'm thinking of
Good luck!
What number do you think it is?:
The Traceback is telling you this:
We got to start().
start() called guessCheck().
We tried to pass two pieces of information to guessCheck(): the variable names number and numberInput.
We don't have those variables defined yet! numberInput doesn't get defined until once we've already started guessCheck(), and number isn't actually defined anywhere.
As Manoj pointed out in the comments, you probably want number to hold the output of selectRandomNumber(). So, instead of just calling selectRandomNumber() in start(), try number = selectRandomNumber() instead.
You can add a print(number) on the line right after that to make sure number has a value assigned to it.
Now number has a value, going into your call to guessCheck(). That still leaves numberInput undefined though. You can set a default value for function arguments like this:
guessCheck(number, numberInput=1)
That way, when guessCheck is called but numberInput hasn't been defined yet, it will automatically give it the value 1 until you set it explicitly.
You may encounter other issues with your code the way it is. My advice would be to start really simply - build up your game from each individual piece, and only put the pieces together when you're sure you have each one working. That may seem slower, but trying to go too fast will cause misunderstandings like this one.

Unable to get out of loops

I'm trying to write a MasterMind game using classes and objects and I'm currently stuck around some of my loops.
while True:
# create a combination
# test the combination
while game_won == False:
print(scoreboard)
# player input combination
# combination is tested then added to scoreboard
tries_left = tries_left+1
if game_won == True:
print(You Won!)
input = Play Again? Y/N
if tries_left == 10:
print(You Lost!)
input = Play Again? Y/N
How do I do to go back to my while True -> create combination from my last if statement? (if tries_left == 10:)
What's wrong
Your first while True doesn't have anything in it, You need to indent code under it if you want it to be inside the loop.
There is a few typos, missing comment characters, and quotation marks.
What needs to happen
When the nested while loop while game_won == True exits, the code will return looping the parent loop while True, which will replay the game, if the user wishes.
Your code fixed (with a few improvements)
Following is how you can loop the game forever (given the user wishes it).
# Assume user wants to play when the program runs
user_wants_to_play = True
ans = ""
# loop the entire game while the user wishes to play
while user_wants_to_play:
# Create the combination
# Test the combination
# Game isn't done when started
game_done = False
tries_left = 10 # Arbitrary number I chose
while not game_done:
# Play the game
print("Scoreboard")
# Subtract one to tries left
tries_left -= 1
if game_done:
print("You won!")
elif tries_left == 0:
print("You lost!")
game_done = True
# if users answer was 'n'
ans = input("Play again? Y/N \n")
if ans.strip().upper() == 'N':
user_wants_to_play = False
Improvements
Boolean logic is more pythonic using not instead of myBool == False
while True: changed to while user_wants_to_play:
User input is scrubbed to ignore white-space and lower case
Changed game_won to game_done
Made tries_left count down instead

Resources