summaryrefslogblamecommitdiffstats
path: root/Controller/classClient.py
blob: 625e48e905068ad4992a992cfcb9ae73f7c70d7b (plain) (tree)









































































                                                                                                                                     
import socket
import sys
import os
import string 

class Connection:
	def __init__(self, h, p):
		self.host = h
		self.port = p
		self.s = None
		self.connected = 0

	def connect(self):
		self.s = None
		
		alive = self.ping()		
		if alive == 0:
			return 'The machine is not alive'
		for res in socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM):
			af, socktype, proto, canonname, sa = res
		    	try:
		        	self.s = socket.socket(af, socktype, proto)
				self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #this resolves the bug with live packets
		    	except socket.error, msg:
		        	self.s = None
				self.connected = 0
		        	continue
		    	try:
		        	self.s.connect(sa)
		    	except socket.error, msg:
		        	self.s.close()
				self.connected = 0
		        	self.s = None
		        	continue
		    	break
		if self.s is None:
			self.connected = 0
			return 'Could not open socket'
		else: 
			self.connected = 1
			return 'Connected'

	def sendData(self, data):
		if self.connected == 1:
			self.s.send(data)

	def receiveData(self):
		if self.connected == 1:
			return self.s.recv(1024)
		else:
			return 'Not connected'

	def closeConnection(self):
		if self.connected == 1:
			self.s.close()
			self.connected = 0
		return 'Closed'

	def ping(self):
		ping_cmd = os.popen('ping '+ self.host + ' -c 1 -W 1').read()
		pingAlive = int(string.find(ping_cmd, '1 received'))
		if pingAlive != -1:
			return 1
		else: 
			return 0

#MAIN PART 
x = Connection('localhost',50008)
print x.connect()
x.sendData('hello server :)')
print x.receiveData()
x.sendData('I send you another message')
x.closeConnection()