#! /usr/bin/python

# Opens a new connection for each line of input

# Derived from sample programs in
#   http://docs.python.org/library/socket.html

import socket
import os

MYNETNUM = 0

HOST = 'localhost'
PORT = 37300 + MYNETNUM

tSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tSock.connect((HOST, PORT))
tFile = tSock.makefile()
data = tFile.readline()                       # TCP read    GAME pong
print 'RCV: ' + data
user = os.getenv('USER')
msg = 'NAME ' + user + '\n\r'
tFile.write(msg)                              # TCP write   NAME user
tFile.flush()
print 'SND: ' + msg
data = tFile.readline()                       # TCP read    UDP xxxxx
print 'RCV: ' + data
udpPort = int(data.split(' ')[1])
uSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
msg = 'OK UDP'
uSock.sendto( msg, (HOST, udpPort))
print 'SND: ' + msg
data = tFile.readline()                       # TCP read    OK
print 'RCV: ' + data
data = tFile.readline()                       # TCP read    WAIT or START
print 'RCV: ' + data
if (data.find('START') < 0):
  data = tFile.readline()                     # TCP read    START
  print 'RCV: ' + data
print '\n** Type lines to send via UDP **\n'
while 1:
  msg = raw_input()
  uSock.sendto( msg, (HOST, udpPort))
  print 'SND: ' + msg
