<commit_before># -*- coding: utf-8 -*-
"""
Created on Fri Dec 28 13:12:58 2012

@author: Preston
"""
import Player, Pile, socket, threading, pickle, sys
import time, random, Queue
from OptionsParser import config_parser
from Card import Card

class Server(object):
    def __init__(self, rule_handler, player_handler, port = None,
                 ip_address = None):
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.bind((ip_address or socket.getfqdn(), int(port)))
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server.listen(5)
        self.clients = {}
        self._server_running = threading.Event()
        threading.Thread(name = 'Connection Thread',
                         target = (self.get_connections),
                         args = (self.server,)).start()
        self.player_handler = player_handler
        self.rule_handler = rule_handler
        self.deck = Pile.Pile()
        self.pile = Pile.Pile()
        self.update_deck()
        self._main_event = threading.Event()


    def is_running(self):
        "Returns True if the server is running, or False if it is not"
        return not self._server_running.is_set()

    def get_connections(self, server):
        "Constantly get connections and adds them to clients"
        while self.is_running():
            try:
                server.settimeout(None)
                client, address = server.accept()
                if address in self.clients:
                    client.send('Same ip as other user! Connection aborted')
                    client.close()
                    continue
                client.send('Connection Established')
                print 'Connection Established with {}'.format(
                ':'.join((address[0], str(address[1]))))

                if client not in self.clients and (
                config_parser.getint('Players', 'max_players')
                or sys.maxint) > len(self.clients):
                    player = self.authorise_player(client)
                    self.clients.update({client: player})
                    self.player_handler.add_player(player)
                    Server.send(player, client)
                    self.receive(client) #Pile request
                    Server.send(self.pile.cards, client)
                    if not self.player_handler.current_player:
                        self.player_handler.next_player()
                    threading.Thread(name = 'Listening to {0} at {1}'.format(
                        player.name, address), target = self.listen,
                        args = (client, player)).start()
                else:
                    Server.send('', client)
                    client.close()
            except (socket.timeout, socket.error):
                try:
                    client.close()
                    if client in self.clients:
                        self.clients.pop(client)
                except (socket.error, UnboundLocalError):
                    pass

    def authorise_player(self, client):
        """Generates and then authorises the player with the information
        provided by the client (It has to send the name). It then returns
        the player if it succeeds, or raises socket.error"""
        player_name = self.receive(client)[0]
        if any(player.name == player_name for player in (
        self.player_handler.players)):
            print '{} is already taken!'.format(player_name)
            raise socket.error
        print player_name + ' Joined!'
        self.send_all('[{} Joined!]'.format(player_name))
        return Player.Player(player_name, hand = self.deck.remove(0,
                               config_parser.getint('Cards', 'hand_size')))

    @staticmethod
    def send(data, client):
        "Send some data (pickled) to the client"
        pickled = pickle.dumps(data) +  ';'
        client.send(str(len(pickled)) + ':')

        total = 0
        while total < len(pickled):
            sent = client.send(pickled[total:])
            if sent == 0:
                raise socket.error("Connection Broken")
            else:
                total += sent<commit_msg>Added some default rules for Deck, Players (the handler, not an individual), and the top card for the pile<commit_after># -*- coding: utf-8 -*-
"""
Created on Fri Dec 28 13:12:58 2012

@author: Preston
"""
import Player, Pile, socket, threading, pickle, sys
import time, random, Queue
from OptionsParser import config_parser
from Card import Card

class Server(object):
    def __init__(self, rule_handler, player_handler, port = None,
                 ip_address = None):
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.bind((ip_address or socket.getfqdn(), int(port)))
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server.listen(5)
        self.clients = {}
        self._server_running = threading.Event()
        threading.Thread(name = 'Connection Thread',
                         target = (self.get_connections),
                         args = (self.server,)).start()
        self.player_handler = player_handler
        self.rule_handler = rule_handler
        self.deck = Pile.Pile()
        self.pile = Pile.Pile()
        self.update_deck()
        self._main_event = threading.Event()


    def is_running(self):
        "Returns True if the server is running, or False if it is not"
        return not self._server_running.is_set()

    def get_connections(self, server):
        "Constantly get connections and adds them to clients"
        while self.is_running():
            try:
                server.settimeout(None)
                client, address = server.accept()
                if address in self.clients:
                    client.send('Same ip as other user! Connection aborted')
                    client.close()
                    continue
                client.send('Connection Established')
                print 'Connection Established with {}'.format(
                ':'.join((address[0], str(address[1]))))

                if client not in self.clients and (
                config_parser.getint('Players', 'max_players')
                or sys.maxint) > len(self.clients):
                    player = self.authorise_player(client)
                    self.clients.update({client: player})
                    self.player_handler.add_player(player)
                    Server.send(player, client)
                    self.receive(client) #Pile request
                    Server.send(self.pile.cards, client)
                    if not self.player_handler.current_player:
                        self.player_handler.next_player()
                    threading.Thread(name = 'Listening to {0} at {1}'.format(
                        player.name, address), target = self.listen,
                        args = (client, player)).start()
                else:
                    Server.send('', client)
                    client.close()
            except (socket.timeout, socket.error):
                try:
                    client.close()
                    if client in self.clients:
                        self.clients.pop(client)
                except (socket.error, UnboundLocalError):
                    pass

    def authorise_player(self, client):
        """Generates and then authorises the player with the information
        provided by the client (It has to send the name). It then returns
        the player if it succeeds, or raises socket.error"""
        player_name = self.receive(client)[0]
        if any(player.name == player_name for player in (
        self.player_handler.players)):
            print '{} is already taken!'.format(player_name)
            raise socket.error
        print player_name + ' Joined!'
        self.send_all('[{} Joined!]'.format(player_name))
        self.update_deck()
        return Player.Player(player_name, hand = self.deck.remove(0,
                               config_parser.getint('Cards', 'hand_size')))

    @staticmethod
    def send(data, client):
        "Send some data (pickled) to the client"
        pickled = pickle.dumps(data) +  ';'
        client.send(str(len(pickled)) + ':')

        total = 0
        while total < len(pickled):
            sent = client.send(pickled[total:])
            if sent == 0:
                raise socket.error("Connection Broken")
            else:
                total += sent
{'fraction_non_alphanumeric': 0.10122123062470643, 'fraction_numerical': 0.005401596993893847, 'mean_word_length': 1.7787928221859706, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '278566', 'n_tokens_mistral': 2318, 'n_tokens_neox': 2169, 'n_words': 574}