# Simple Chat Server (code based on BobChat - http://www.penzilla.net/tutorials/python/BobChat/) # Waits for input, randomly replies gibberish import sys import random from select import select from socket import socket, AF_INET, SOCK_STREAM HOSTNAME = "localhost" SERVERPORT = 5678 # create/initialize sockets variables message_queue = [] # server_socket is the list of sockets that the server listens to. # this can be 1 or more sockets.. server_socket = [] # incoming_messages is the list of sockets that select will monitor for incoming messages. # each client will have one entry in this list. incoming_messages = [] # potential_writers is the list of sockets that the server will write to (send messages to clients). # the select call will monitor this list to see if these sends have completed. potential_writers = [] 0 # Cards! cards = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] suit = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] # open socket sock = socket(AF_INET, SOCK_STREAM) sock.bind((HOSTNAME, SERVERPORT)) sock.listen(5) server_socket.append(sock) incoming_messages.append(sock) def MacheWerk(command): message = '' if command == "roll": message = "You rolled a",random.randint(1,6) elif command == "card": message = message + cards[random.randint(0, len(cards)-1)] + " of " message = message + suit[random.randint(0,3)] elif command == "deal": message = "You were dealt: " for i in range(0,4): print "dealing" message = message + cards[random.randint(0, len(cards)-1)] + " of " message = message + suit[random.randint(0,3)] message = message + ", " return message def start_server(): while 1: # select sockets with incoming message and that have completed output... ready_to_read, ready_to_write, in_error = select(incoming_messages, potential_writers, []) for curr_socket in ready_to_read: if curr_socket in server_socket: # waiting for new clients new_socket, address = curr_socket.accept() print "\n Server Found New Client: Address:", address, " SOCKET_ID: ", id(new_socket) incoming_messages.append(new_socket) else: # ongoing connection try: # try statement is overly general. try to catch EOF errors from sockets # when they run out of data. data = curr_socket.recv(1024) print "\n Received message from ", data, "on", id(curr_socket) if not data: curr_socket.close() incoming_messages.remove(curr_socket) if curr_socket in potential_writers: potential_writers.remove(curr_socket) else: message_queue.append(data) # make the socket writable if not (curr_socket in potential_writers): potential_writers.append(curr_socket) except: pass # get ready to write while 1: if (len(ready_to_write)==0) or (len(message_queue) == 0): break message = message_queue[0] # respond message for curr_socket in ready_to_write: try: curr_socket.send( "Hello %s. %s" % (message, MacheWerk(message))) print "\n Replied to", id(curr_socket) except: pass message_queue.remove(message) if __name__=="__main__": try: start_server() finally: sock.close()