0

i have downloaded this project from github of a quiz game using server-client where server needs to connect with two instances of client as player1 and player2 but I'm getting a minor bug player1 is connected successfully but when trying to connect player 2 it gives a error please someone help

client.py code

def question(s):
    ques = s.recv(1024)
    print (ques)
    ans = input("Answer: ")
    while ans not in ['A', 'B', 'C', 'D']:
        print ("Enter a valid choice!")
        ans = input("Answer: ")
    s.sendall(ans)
    response = s.recv(1024)
    print (response)

while True:
    choice = s.recv(1024)
    if choice[0] == "Q":
        question(s)
    elif choice[0] == "S":
        scores(s)
    elif choice[0] == "C":
        challenge(s)
    elif choice[0] == "X":
        final(s)
        break
    elif choice[0] == "A":
        final(s)
    else:
        print ("Invalid choice: ", choice)

server.py code

print ("Server bound to ", HOST, ":", PORT, "\nConnect both players before continuing...")
(conn1, addr) = s.accept()
print ("Connected to Player 1 at ", addr)
(conn2, addr) = s.accept()
connlist = [conn1, conn2]
conn1.sendall("A\n")   //line 47
time.sleep(0.1)
conn1.sendall("You are Player 1\n")
time.sleep(0.1)
conn2.sendall("A\n")
time.sleep(0.1)
conn2.sendall("You are Player 2\n")
time.sleep(0.1)
print ("Connected to Player 2 at ", addr)
for questionNo in range(totalQuestions):
    conn1.sendall("A\n")
    time.sleep(0.1)
    conn1.sendall("Question Number "+str(questionNo+1)+" for Player "+str(questionNo%2+1)+"\n")
    time.sleep(0.1)
    conn2.sendall("A\n")
    time.sleep(0.1)
    conn2.sendall("Question Number "+str(questionNo+1)+" for Player "+str(questionNo%2+1)+"\n")
    time.sleep(0.1)

the error I'm getting is: server side

$ python3 server.py
Enter the port number to bind with: 8888
Enter the total number of questions: 5
Enter the name of the quiz file: ques.txt
Server bound to  localhost : 8888 
Connect both players before continuing...
Connected to Player 1 at  ('127.0.0.1', 56912)
Traceback (most recent call last):
  File "server.py", line 47, in <module>
    conn1.sendall("A\n")
TypeError: a bytes-like object is required, not 'str'

client side:

$ python3 client.py
Enter the port number to which the server is bound: 8888
Traceback (most recent call last):
  File "client.py", line 39, in <module>
    if choice[0] == "Q":
IndexError: index out of range

1 Answers1

0

While communicating through sockets, you need to send data in form bytes and not in a string format

In server.py, replace all instances of conn.sendall() with

conn.sendall(message.encode()) #encode method converts str to bytes

Similarly in client.py, you might want to function with the string format of received data and not the original bytes

ques = s.recv(1024).decode()  # .decode() converts bytes to str

You can read more about encoding and decoding here

CopyrightC
  • 857
  • 2
  • 7
  • 15