The following code is giving a global name not defined error, but as far as I can see the name is defined. I'm new to Python, is this a scope issue?
import os, socket
from threading import Thread
class serv:
def __init__(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(('', 443))
def run(self):
self.socket.listen(10)
print "Listening"
self.conn, self.addr = self.socket.accept()
try:
Thread(target=clientThread, args=(self.conn,)).start()
except Exception, errtxt:
print errtxt
def exit(self):
print "Disconnected"
self.conn.close()
def clientThread(conn):
print "Connected"
while 1:
conn.send("Hello, worlds!\n")
S = serv()
S.run()
The specific error is
global name 'clientThread' is not defined
you should use
self.clientThread
I would make these changes:
(1) Pass self
to self.clientThread
def run(self):
self.socket.listen(10)
print "Listening"
self.conn, self.addr = self.socket.accept()
try:
Thread(target=self.clientThread, args=(self,)).start()
except Exception, errtxt:
print errtxt
(2) Reference self
in clientThread
def clientThread(self):
print "Connected"
while 1:
self.conn.send("Hello, worlds!\n")
Another possibility is to have your object derive from threading.Thread
instead of have a Thread. Then your code looks more like this:
import os, socket
from threading import Thread
class serv(Thread):
def __init__(self):
super(serv, self).__init__()
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(('', 443))
def run(self):
self.socket.listen(10)
print "Listening"
self.conn, self.addr = self.socket.accept()
try:
print "Connected"
while 1:
self.conn.send("Hello, worlds!\n")
except Exception, errtxt:
print errtxt
def exit(self):
print "Disconnected"
self.conn.close()
S = serv()
S.start()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With