# Echo server program
import socket

HOST = ''        # Symbolic name meaning all available interfaces
PORT = 50008              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
numports = 2
j= 0
while(j < numports):
 conn, addr = s.accept()
 print 'Connected by', addr
 j+=1

print "All ", numports, " clients are now connected."

nummoves = 3
j = 0
while(j < nummoves):
  print "Move j is: ", j
  otherports = []
  bids = []
  bidports = []
  i = 0
  while (i < numports):
    data = conn.recv(1024)
    if not data: break
    indata = data.split(" ")
    conn.send("Thank you, " + indata[0] +  " I have received your bid of " + indata[1])
    bids.append(int(indata[1]))
    bidports.append(int(indata[0]))
    i+= 1
  bestbid = max(bids)

  print otherports

  i = 0
  while(i < len(otherports)):
    s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s2.connect((HOST, int(bidports[i])))
    if(bids[i] == bestbid):
    	s2.send(bidports[i] + ' you have bought this item')
	ackdata = s2.recv(1024)
        print ' '.join(ackdata)
    else:
    	s2.send(bidports[i] + ' someone else has bought this item')
	ackdata = s2.recv(1024)
        print ' '.join(ackdata)
    s2.close()
    i+= 1
  j+=1
# conn.close()
