#!/usr/bin/env python

# Copyright (c) 2001-2009 Twisted Matrix Laboratories.
# See LICENSE for details.


from winswitch.util.main_loop import test_loop, loop_exit, connectTCP
from winswitch.consts import LOCALHOST
from twisted.internet.protocol import ClientFactory
from twisted.protocols.basic import LineReceiver


class EchoClient(LineReceiver):
	end="Bye-bye!"
	def connectionMade(self):
		self.sendLine("Hello, world!")
		self.sendLine("What a fine day it is.")
		self.sendLine(self.end)

	def lineReceived(self, line):
		print "receive:", line
		if line==self.end:
			self.transport.loseConnection()

class EchoClientFactory(ClientFactory):
	protocol = EchoClient

	def clientConnectionFailed(self, connector, reason):
		print 'connection failed:', reason.getErrorMessage()
		loop_exit()

	def clientConnectionLost(self, connector, reason):
		print 'connection lost:', reason.getErrorMessage()
		loop_exit()

def connect_echo_client():
	factory = EchoClientFactory()
	connectTCP(LOCALHOST, 54296, factory)

def main():
	test_loop(connect_echo_client)


if __name__ == '__main__':
	main()
