Okay, so I'm currently working my way through Beginning Python: From Novice to Professional, and I'm up to the networking stuff. I consider myself at least an intermediate Python programmer, but the network stuff is really confusing me. I'm trying to get the hang of it by writing a simple chat server, which I would then like to someday evolve into a full chat program with a GUI and such. Here is my code so far:
import socket
import select
class ChatServer(object):
def __init__( self, port ):
self.port = port
self.host = socket.gethostname()
self.serversocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
self.serversocket.bind( (self.host, self.port) )
self.serversocket.listen( 5 )
self.chatters = [self.serversocket]
print "Chat server started on port %s" % port
def run( self ):
while True:
(sread, swrite, sexc) = select.select( self.chatters, [], [], 10 )
#print "test ", sread
for sock in sread:
if sock == self.serversocket:
self.accept_connection()
else:
val = self.serversocket.recv(500)
(host, port) = sock.getpeername()
if val == "":
val = "Client disconnected %s:%s\n" % (host, port)
self.broadcast( val, sock )
sock.close
self.chatters.remove( sock )
else:
val = "[%s:%s] %s" % (host, port, val)
self.broadcast( val, sock )
def accept_connection( self ):
pass
def broadcast( self, val, omitted ):
pass
As you can see I haven't written accept_connection or broadcast yet, but the idea should be pretty obvious. I think I'm misinterpreting how select works though, because my little "test" thing just keeps telling me that it timed out. It's hard to find documentation of these areas for Windows environments. The idea is that it should wait for activity in self.chatters (one of the sockets), and then deal with that action appropriately, by reading the message, or accepting or closing the connection. The sread list keeps appearing empty however, and I feel like I should get that working before I try to accept any connections. Is there anything obvious I'm missing? Thanks!