Reputation: 65
Here's the code giving me the issue:
def connect():
s.listen(2)
print("Server listening")
conn,addr=s.accept()
print("Connected with " + str(addr) + '\n')
recv()
def recv():
while 1:
try:
print("Starting try statement")
data=conn.recv(1024)
if data == "":
print("No data")
recv()
else:
print("Data")
print(data.decode('UTF-8') + " -END")
recv()
except:
print("No connection")
connect()
conn.close()
When I execute the code, it'll connect to the client and be ready to receive a message at any point. However, once it's executed this is what appears.
Server listening
Connected with ('xx.xxx.xxx.xx', xxxxx)
Starting try statement
No connection
Server listening
IP censored. Does anyone have a fix for this?
EDIT: Typo
CLIENT CODE (From TKinter GUI)
s.connect((host,port))
self.chatlog['state'] = NORMAL
self.chatlog.insert(END, ("===CONNECTED TO SERVER\n"))
self.chatlog['state'] = DISABLED
self.chatlog.yview(END)
self.conn=True
print("Connected")
Upvotes: 0
Views: 546
Reputation: 33
You are doing it wrong.
Ya 'now that local conn what you are creating in function connect is not accessible from function recv? That is a reason for not reciving anything.
My solution using that code, without using classes and threads but with select and sys module is:
import sys
import select
def connect()
s.listen(2)
print('Sever listening')
inputs = [s, sys.stdin]
running = 1
while running:
i_rdy = select.select(inputs,[],[],1)[0]
if s in i_rdy:
conn, addr = s.accept()
print ('Connected with ' + str(addr) + '\n')
recv(conn)
if sys.stdin in i_rdy:
junk = std.stdin.readline()
if junk.lstrip('\n') == 'exit':
running = 0
print('Closing server')
s.close()
def recv(conn):
while 1:
try:
print("Starting try statement")
data = conn.recv(1024)
if data == "":
print("No data")
else:
print("Data")
print(data.decode('UTF-8') + " -END")
except:
print("No connection")
#traceback
print(sys.exc_info)
break
try:
conn.close()
except:
pass
As you can see can "exit" when u type exit to console but only when there is no active connection...
That why you should consider rewrite this to classes, it would be a lot easier to stop, not "ugly" and it could handle multiple connections.
Upvotes: 1