include tcp.repy

if callfunc == 'initialize':
  IP = getmyip()
  PORT = 12345
  PORT_TWO = 12346
  MESSAGE = "hi"
  MAXLEN = 4096

def server():
  socket = Connection()
  socket.bind(IP, PORT_TWO)
  
  socket.listen()
  tcup, addr = socket.accept()

  bytes = tcup.send(MESSAGE)
  if bytes == 0:
    print "Expected some bytes"
  
  tcup.disconnect()

def client():
  socket = Connection()
  socket.bind(IP, PORT)

  socket.connect(IP, PORT_TWO)

  tries = 100
  while tries:
    mess = socket.recv(MAXLEN)
    if mess == MESSAGE:
      break
    tries -= 1
    sleep(.01)

  if mess != MESSAGE:
    print "%s != %s" % (mess, MESSAGE)

  socket.disconnect()

def main():
  settimer(0, server, ())
  sleep(.01)
  client()

if callfunc == 'initialize':
  main()
  exitall()
