Reputation: 77
I am trying to make two simple functions that use sockets and act as a server/client for sending some text.
I can send text and print it out but when I store it in a variable and try to access it outside the while
loop which it was created in, the variable becomes None
.
Here is my (full, because it's really small) code:
send.py (the client):
import socket
def send(HOST2 = "localhost", PORT2 = 50007,):
s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s2.connect((HOST2, PORT2))
s2.sendall(b"Hello, world!")
s2.close()
send()
The code above works as expected.
recive.py (the server):
import socket
def recive(HOST = "localhost", PORT = 50007):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
while True:
global data
data = conn.recv(1024).decode("ascii")
print(data) #This will print correctly as expected
if not data: break
conn.close()
recive()
print(data) #This is None
My question is how to use the variable data outside the loop. For some reason it is None. My guess is that it has to do something with local/global variables or it is the way socket module behaves.
EDIT: I have changed the code and the problem is still there.
Changes: Added recive()
and send()
calls.
Upvotes: 0
Views: 1611
Reputation: 364
Few things:
Firstly it's generally convention to declare your globals at the top of a function, not partway through
Secondly, is there more to your code? because from what you posted you're defining a function and then trying to access a global which would be set by it without actually calling it.
Update:
I ran your updated code and it worked fine for me
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(('localhost', 50007))
>>> s.sendall('test')
>>>
pi@raspberrypi ~ $ python recive.py
test
Update #2:
I'm guessing that your socket is blocking; meaning for the typical case it will wait for some data to return before it returns, which means it won't ever be False when you try to break. This means that your while loop will never terminate and the second print will not execute. To test this theory throw a break after the first print and before the if not data: break
Upvotes: 1
Reputation: 599610
Your print statement is not only outside the loop, it is outside the function. It will be executed before the function is even called, and has no access to the data variable within the function.
Indent it one more level so it is within the function.
Upvotes: 1