• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Help with Python Network Code

Fox5

Diamond Member
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.

#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()
 
The wierd thing is that I have a client class programmed very similar, but rather than getting stuck in the while loop in the run method forever, it exits after one loop and allows normal execution.
#This class will connect to a server and send it a file. It will continually send files until its queue is empty.

import Queue
import socket
import threading
import cPickle

port = 2730
address = 'localhost'
List = []

class Client(threading.Thread):
   
    def run(self):
        while True:
            print 'client'
            object = clientPool.get()
           
            if object != None:
                pickle = cPickle.dumps(object)
                client.connect((address,port))
                client.send(pickle)
                client.close()
       

# Create our Queue: This automatically manages threads for us.
clientPool = Queue.Queue ( 0 )
client = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
# Start three threads:
for x in xrange ( 3 ):
   Client().start()

#This method doesn't directly send a file, but rather adds it to the thread queue.
def sendFile(objectToSend):
#   clientPool.put(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
#   List.insert(0,objectToSend)
    clientPool.put(objectToSend)

def changePort(portInt):
    port = portInt

def changeAddress(addressString):
    address = addressString
 
def __serve():
while True:
clientPool.put(server.accept())
threading.Thread(__serve()).start()
I'm not certain, but I imagine you would block here importing the file. __serve() is evaluated, which sends the main thread into the while loop. server.accept() is a blocking call, which would be gumming you up anyways. What you are likely intending to do is call thread.start_new_thread( __serve, () )

Unrelated, it would probably be good to include a time.sleep() within the client and server run loops.
 
Ok, thanks, I think that may have helped, though I moved the code out of run and into a seperate method anyway.
What would be a good value to pass time.sleep()?

Also, I changed my code to
#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 myServer(threading.Thread):

    def run(self):
        pass



# Create our Queue: This automatically manages threads for us.
clientPool = Queue.Queue ( 0 )

# Start three threads:
for x in xrange ( 3 ):
    myServer().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 doNothing():
    pass

    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.start_new_thread(__serve,())

    def listen():
        threading.Thread.start_new_thread(__listen,())

    def __listen():
            while True:
                clientPool.put(server.accept())
                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 ]

But I get an error when trying to call its methods from another class.
My test class is
from myServer import myServer

from Client import Client



s = myServer()

c = Client()


s.changePort(5020)
c.changePort(s.getPort())
c.changeAddress(s.HostName())
s.listen()

c.sendFile("This")
c.sendFile("Is")
c.sendFile("A")
c.sendFile("Message")
print "Hello"
firstLoop = s.nextItem()
print firstLoop
while firstLoop != 0:
print firstLoop
firstLoop = s.NextItem()

But I get the error
Traceback (most recent call last):
File "<string>", line 11, in ?
File "Test.py", line 13, in ?
s.changePort(5020)
AttributeError: 'myServer' object has no attribute 'changePort'

I'm assuming that perhaps my syntax somewhere is messed up?
 
myServer has only functions you've defined (run) and those inherited from threading.Thread. changePort is defined outside of the class, I'm a bit confused to what it belongs to.

A value between .1 and 1.0 for sleep should be more than adequate.
 
How do I define it to be part of the class? I've tried indenting, but that still doesn't allow it to work.
 
Indenting alone won't define it as part of the class. It looks as if you're interleaving functions definitions and imperative statements. Each of the statements which are not function/class definitions are executed when you import the class.

Take a look at OOP Tutorial. It seems like you understand the syntax, so this document should help you.

Perhaps a better policy would to _only_ define the class and functions within the file. I don't think people typically expect an import statement to have side effects.
 
Back
Top