I'd like some constructive peer review just to help me make sure I'm doing this correctly / well.
You can test it by connecting to localhost if you want to run the code to help with review. One thing I'd like to know how to do is fix the output to the screen. Currently it interrupts typing when a message is recieved which as I understand is because my typing a line is basically letting the client thread sleep, and recieving a message triggers the server thread while I'm typing... Maybe there is some sort of better thread management for this? Or is this just a limiting factor since I'm playing in the console world? The other issue I have is when the other person types DSC to end their session, I should be able to put the thread to sleep, or trash it or something so I dont have to close the app to use it again. It also isn't going through the entire
I was hoping to actually make something more like an IRC server / client, but I'm not sure I've got this thing down well enough to try that. Thanks!
from socket import *
import Queue, threading, os
class ServerThread ( threading.Thread ):
def run ( self ):
while True:
client = clientPool.get()
clientName = client[0].recv(1024)
print '\n' + ('=' * 40)
print 'Connection Established by %s...' % clientName
client[0].send('Connection Established!')
while True:
try:
data = ""
except:
print "Connection to %s terminated!" % clientName
break
if data:
if 'DSC' not in data:
print data
else:
print ('=' * 40)
client[0].send('Connection Terminated...')
print '\nClosed connection to %s... ' % clientName
return False
else:
client[0].send('Closing connection.')
return False
client[0].close()
class ClientThread ( threading.Thread ):
def run ( self ):
print "Type 'DSC' to disconnect..."
print '=' * 40
myServer = raw_input('Server Name / IP: ')
myName = os.environ.items ()[1][1].title()
server = socket(AF_INET, SOCK_STREAM)
try:
server.connect((myServer, 2000))
server.send(myName)
msg = ''
while True:
data = ""> print data
print '=' * 40
while msg != 'DSC':
msg = raw_input()
server.send(myName + ': ' + msg)
data = ""> print data
server.close()
except:
server.close()
# Create our Queue:
clientPool = Queue.Queue ( 0 )
# Start threads:
print '=' * 40
print "Initializing Listening Device..."
ServerThread().start()
myPort = 2000
myIP = gethostbyname(os.environ.items()[1][1])
print "Listening for %s on port %s" % (myIP,myPort)
ClientThread().start()
# Set up the server:
myServer = socket(AF_INET, SOCK_STREAM)
myServer.bind(('', myPort))
myServer.listen(5)
# Have the server serve "forever":
while True:
clientPool.put(myServer.accept())
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor