# L-20.0 MCS 260 Mon 1 Aug 2014 : tcp_dealer.py
"""
The server is a dealer who lets the client
guess a secret number, each time giving feedback
The behavior of the corresponding client is defined
by the script tcp_player.py.
"""
from random import randint
from socket import socket as Socket
from socket import AF_INET, SOCK_STREAM

SECRET = randint(0, 9)
print 'the secret is %d' % SECRET

HOSTNAME = ''   # blank so any address can be used
NUMBER = 11267  # number for the port
BUFFER = 80     # size of the buffer

DEALER_ADDRESS = (HOSTNAME, NUMBER)
DEALER = Socket(AF_INET, SOCK_STREAM)
DEALER.bind(DEALER_ADDRESS)
DEALER.listen(1)

print 'dealer waits for player to connect'
PLAYER, PLAYER_ADDRESS = DEALER.accept()
print 'dealer accepted connection request from ', \
    PLAYER_ADDRESS

while True:
    print 'dealer waits for a guess'
    GUESS = PLAYER.recv(BUFFER)
    print 'dealer received ' + GUESS
    if int(GUESS) < SECRET:
        REPLY = 'too low'
    elif int(GUESS) > SECRET:
        REPLY = 'too high'
    else:
        REPLY = 'found the secret'
    PLAYER.send(REPLY)
    if REPLY == 'found the secret':
        break

DEALER.close()
