Ok, below I've attached my server code. It gets stuck on the while loop in run and just keeps going through. I'm not sure how else to make a server that's "always listening" as the example code I can find online is programmed very similarly to this. I believe this code would work if a seperate process was started up and attempted to connect to the network, but currently I'm trying to import the server and client class into another class and then create instances of those objects. The code just hangs on the import statement of the server class. I'm really not sure what the problem is, I would have thought that threading the class would have taken care of the while loop blocking execution.
I'd appreciate it if anyone could point out any errors or alternative ways to do this.
I'd appreciate it if anyone could point out any errors or alternative ways to do this.
#This is a threaded network class communicating over sockets. It uses TCP/IP.
#This class will actively listen for incoming connections, and automatically store the data in a list.
import Queue
import socket
import threading
import cPickle
port = 2730
List = []
class Server(threading.Thread):
def run(self):
while True:
if clientPool.empty() == False:
client = clientPool.get()
if client != None:
print 'Received connection:', client [ 1 ] [ 0 ]
total_data = []
while True:
data = client[0].recv(1024)
if not data: break
total_data.append(data)
client [ 0 ].close()
obj = ''.join(total_data)
List.insert(0,cPickle.loads(obj))
print 'Closed connection:', client [ 1 ] [ 0 ]
# Create our Queue: This automatically manages threads for us.
clientPool = Queue.Queue ( 0 )
# Start three threads:
for x in xrange ( 3 ):
Server().start()
# Set up the server:
server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
server.bind ( ( socket.gethostname(), port ) )
server.listen ( 5 )
print "The host is " + socket.gethostname()
def HostName():
return socket.gethostname()
def changePort(port):
server.bind((socket.gethostname(), port))
def getPort():
return port
def nextItem():
return list.pop()
def __serve():
while True:
clientPool.put(server.accept())
threading.Thread(__serve()).start()