import socket
import sys
import time

address = ("localhost", 8888)

def server():
  ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  ss.bind(address)
  ss.listen(5)
  (s, other_address) = ss.accept()
  # Send a message, but then close the socket shortly after.
  # Will the client manage to read the goodbye message, if it tries to write
  # first?
  s.send("This is the server saying goodbye\n")
  time.sleep(1)
  s.close()

def client():
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.connect(address)
  # Try to send a message immediately.  At this point we expect the server
  # end to be waiting for a second before closing, so it should be OK.
  try:
    print "Sending A..."
    sent = s.send("A\n")
    print sent
  except Exception, e:
    # (Should not be reached)
    print e
  # Wait until after the server has closed its socket, and try to send
  # another message.
  time.sleep(2)
  try:
    print "Sending B..."
    sent = s.send("B\n")
    print sent
  except Exception, e:
    # We expect an error either here or at the next write (?)
    print e
  # Send one more message, just to see if perhaps an error will be reported
  # here rather than earlier...
  try:
    print "Sending C..."
    sent = s.send("C\n")
    print sent
  except Exception, e:
    # What about now?
    print e
  # Can we read the goodbye message?
  print s.recv(1024)

if __name__ == "__main__":
  if sys.argv[1] == "--server":
    server()
  elif sys.argv[1] == "--client":
    client()
