Reputation: 83
I am try to display data that is sent over a socket via an iteration from a loop. The way I have it at the moment isn't working on the Admin client. What should I do to fix my loop? Thank you
Admin thread in the server -
def HandleAdmin(adminSocket,):
global addressList
(c,a) = adminSocket.accept()
ts = ssl.wrap_socket(c, certfile="5cc515_server.crt",
keyfile="5cc515_server.key",
server_side=True,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs="5cc515-root-ca.cer")
if ts.recv(80).decode() == 'Hello\r\n':
ts.send('Admin-Greetings\r\n'.encode())
if ts.recv(80).decode() == 'Who\r\n':
for i in addressList:
ts.send(i.encode())
ts.close()
return
Admin Client
import ssl
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ts = ssl.wrap_socket(s, certfile="100298750.crt",
keyfile="100298750.key",
ca_certs="5cc515-root-ca.cer")
ts.connect(('127.0.0.1', 4001))
ts.send("Hello\r\n".encode())
if ts.recv(80).decode() == "Admin-Greetings\r\n":
print("The players currently online are:\n")
ts.send("Who\r\n".encode())
loop = True
try:
while(loop == True):
if (ts.recv(1000) != Null):
print(ts.recv(1000).decode())
else:
loop = False
ts.close()
except:
pass
Upvotes: 0
Views: 5471
Reputation: 69042
The first problem is that you try to do != Null
, which will raise a NameError
as Null is not valid in python, it's None
. You don't see that error because of the raw except. You should only except the errors you are actually expecting.
In addition to that, recv
doesn't return None when there is not data or the connection is closed, it returns an empty string.
Then in your loop you call recv
twice, throwing away the result of the first call after the comparison. A better way to write your loop would be:
try:
data = ts.recv(1000)
while data:
print(data.decode())
data = ts.recv(1000)
except IOError as e:
pass
finally:
ts.close()
Or, if you want a more pythonic solution, use a function iterator with the empty string as sentinel:
from functools import partial
for data in iter(partial(ts.recv, 1000), b''):
print(data.decode())
Upvotes: 2